我想编写一个将XML文档转换为CSV文件的XSLT。这是XML的一个示例:
<?xml version="1.0" encoding="utf-8"?>
<catalog>
<cd id="c1">
<singer id="s1">
<name>Kate</name>
<surname>Apple</surname>
</singer>
<title>Great CD</title>
</cd>
<cd id="c2">
<singer id="s2">
<name>Mary</name>
<surname>Orange</surname>
</singer>
<title>Even better CD</title>
</cd>
</catalog>
生成的CSV文件应如下所示:
singer, title
Kate Apple, Great CD
Mary Orange, Even better CD
我提出了以下XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
singer,title
<xsl:for-each select="catalog/cd/singer">
<xsl:value-of select="concat(name,' ',surname,'
')" />
</xsl:for-each>
<xsl:for-each select="catalog/cd">
<xsl:value-of select="title"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
结果输出接近我想要实现的目标:
singer,title
Kate Apple
Mary Orange
Great CDEven better CD
但元素的顺序不正确。我该如何解决这个问题?
答案 0 :(得分:2)
如果每个newsave = Save()
newsave.user = save.user
myList = json.loads(newsave.myField) # Read previous here, here is the problem
... (do some changes on myList) ...
newsave.myField = json.dumps(myList) # Save the new move, UPDATED
只有一个cd
,那么为什么不做这件事:
singer
答案 1 :(得分:0)
你在歌手上循环然后在CD上循环以获得标题。你需要循环播放CD,然后在该循环中获得歌手和标题。
类似的东西:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
singer,title
<xsl:for-each select="catalog/cd">
<xsl:value-of select="concat(singer[1]/name,' ',singer[1]/surname,',',title,'
')" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
如果你的xml中有一个命名空间,如:
<?xml version="1.0" encoding="utf-8"?>
<library xmlns="http://example.net/library/1.0">
<cd id="c1">...
然后你还必须在XSLT上使用命名空间:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:l="http://example.net/library/1.0">
<xsl:template match="/">
singer,title
<xsl:for-each select="l:library/l:cd">
<xsl:value-of select="concat(l:singer[1]/l:name,' ',l:singer[1]/l:surname,',',l:title,'
')" />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
答案 2 :(得分:0)
接近普通CSV的一个解决方案是:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no" />
<xsl:template match="/">
singer,title
<xsl:for-each select="catalog/cd">
<xsl:value-of select="concat(singer/name,' ',singer/surname,',')" />
<xsl:value-of select="concat(title,'
')"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
输出结果为:
singer,title
Kate Apple,Great CD
Mary Orange,Even better CD