【发布时间】:2017-04-12 15:25:07
【问题描述】:
我已经输入了 XML,
<?xml version="1.0" encoding="UTF-8"?>
<Vehicle>
<Ordinary>
<Car>Honda City</Car>
</Ordinary>
<Luxury>
<Car>Volkswagon</Car>
</Luxury>
<Luxury>
<Car>Dzire</Car>
</Luxury>
我必须使用 XSLT 将此 xml 消息转换为,
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<id>1</id>
<title>/Vehicle/Ordinary/</title>
<text>Car</text>
<answer>Honda City</answer>
</item>
<item>
<id>2</id>
<title>/Vehicle/Luxury[1]/</title>
<text>Car</text>
<answer>Volkswagon</answer>
</item>
<item>
<id>3</id>
<title>/Vehicle/Luxury[2]/</title>
<text>Car</text>
<answer>Dzire</answer>
</item>
- 这里的 id 可以是自动生成的唯一编号..
- 所有没有任何值的父标签 Xpath 将进入
标签内。 - 具有价值的元素位于
标签内。 - 实际值在
标记内。 - XSLT 应该足够通用,可以应用任何格式的 XML 文档,而不是特定于给定的示例 xml。
我从下面开始,
<?xml version="1.0" encoding="windows-1252" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:strip-space elements = "*" />
<xsl:template match="/">
<items>
<xsl:apply-templates/>
</items>
</xsl:template>
<xsl:template match="text()">
<item>
<title>
<xsl:for-each select="ancestor-or-self::*">
<xsl:text>/</xsl:text>
<xsl:value-of select="name()" />
</xsl:for-each>
</title>
<answer>
<xsl:value-of select="." />
<xsl:apply-templates/>
</answer>
</item>
</xsl:template>
</xsl:stylesheet>
它生成以下输出,
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<id>1</id>
<title>/Vehicle/Ordinary/Car</title>
<answer>Honda City</answer>
</item>
<item>
<id>2</id>
<title>/Vehicle/Luxury[1]/Car</title>
<answer>Volkswagon</answer>
</item>
<item>
<id>2</id>
<title>/Vehicle/Luxury[2]/Car</title>
<answer>Dzire</answer>
</item>
</items>
需要你的帮助...
【问题讨论】:
-
您已经向我们提供了要求,但您没有向我们展示您尝试了什么或遇到了问题。没有实际的问题。这似乎更像是一个"Do you haz teh codez?" 请求。
-
@Daniel : 添加了我用来启动转换的 XSLT
-
"XSLT 应该足够通用,可以应用任何格式的 XML 文档" 没有这样的东西。 XML 非常灵活,一个 XSLT 不可能处理任何 XML 模式 - 除非处理完全没有意义(例如身份转换)。