【发布时间】:2018-09-22 16:50:44
【问题描述】:
我正在尝试使用以下样式表将输入的 XML 文档属性转换为元素:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml"/>
<xsl:template match="*">
<xsl:element name="{name()}">
<xsl:for-each select="@*[name()!='type']">
<xsl:element name="{name()}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
<xsl:apply-templates select="*|text()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
然而,尽管基于每个元素属性正确地创建了新元素,“叶子”元素(即没有子元素)的文本与创建的元素混合在一起。例如
输入 XML
<order>
<id>12345</id>
<date>Today</date>
<location country="PT">LX</location>
<location country="ES">Barcelona</location>
<items type="array" stock="true">
<item>
<id type="array">item1</id>
<spec>
<color type="array">brown</color>
<price currency="euro">20</price>
<usage>office</usage>
<usage>home</usage>
</spec>
</item>
</items>
</order>
输出 XML
<order>
<id>12345</id>
<date>Today</date>
<location>
<country>PT</country>LX
</location>
<location>
<country>ES</country>Barcelona
</location>
<items>
<stock>true</stock>
<item>
<id>item1</id>
<spec>
<color>brown</color>
<price>
<currency>euro</currency>20
</price>
<usage>office</usage>
<usage>home</usage>
</spec>
</item>
</items>
</order>
我想要什么
...
<location>
<text>LX</text>
<country>PT</country>
</location>
<location>
<text>Barcelona</text>
<country>ES</country>
</location>
...
<price>
<text>20</text>
<currency>euro</currency>
</price>
...
我尝试了什么
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml"/>
<xsl:template match="*">
<xsl:element name="{name()}">
<xsl:for-each select="@*[name()!='type']">
<xsl:element name="text">
<xsl:value-of select=".."/>
</xsl:element>
<xsl:element name="{name()}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
<xsl:apply-templates select="*|text()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
问题 尽管正确地创建了新的元素标签
<text>20</text>
它还在“非叶子”元素(即具有子元素的元素)上创建“文本”元素,获取提供的示例:
...
<items>
<text>item1brown20officehome</text>
<stock>true</stock>
<item>
<id>item1</id>
<spec>
<color>brown</color>
<price>
<text>20</text>
<currency>euro</currency>20
</price>
<usage>office</usage>
<usage>home</usage>
</spec>
</item>
</items>
...
我不想
<text>item1brown20officehome</text>
有什么想法吗?提前致谢。
【问题讨论】:
-
欢迎来到 Stack Overflow!很好的第一个问题。尤其是显示您尝试过的部分。 +1
-
非常感谢@DanielHaley!不仅您的帮助对于解决这个问题至关重要,因为您在社区中提供了鼓励!