【发布时间】:2016-12-13 10:39:10
【问题描述】:
我想使用 XSLT 从 xml 输入中删除一些元素并在 Json 的输出中交换一些元素
我输入的有效 xml 文件是:
<items>
<item>
<statement/>
<response/>
<media>
<type>img</type>
<link>SLP.jpg</link>
</media>
</item>
<item>
<statement>walking time bomb.</statement>
<response>
<p>Developing additional problems with your health.</p>
</response>
<media>
<type>html</type>
<link>Brightcove.com%2FZ678766-1.avi</link>
</media>
</item>
</items>
我使用的XSL:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:json="http://json.org/" exclude-result-prefixes="#all">
<xsl:template match="items">
items: [
<xsl:apply-templates/>
]
</xsl:template>
<xsl:template match="item">
{
<xsl:apply-templates/>
},
</xsl:template>
<xsl:template match="statement">
"statement": "<xsl:apply-templates/>"
</xsl:template>
<xsl:template match="response">
"response": "<xsl:apply-templates/>"
</xsl:template>
<xsl:template match="media">
media: {
<xsl:apply-templates/>
}
</xsl:template>
<xsl:template match="type">
"type": "<xsl:apply-templates/>"
</xsl:template>
<xsl:template match="link">
<xsl:text>"link": "files/</xsl:text>
<xsl:value-of select="tokenize(., '/')[last()]"/>"
</xsl:template>
<xsl:template match="p">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
我得到的输出 json 为:
items: [
{
"statement": ""
"response": ""
media: {
"type": "img"
"link": "files/SLP.jpg"
}
},
{
"statement": "walking time bomb."
"response": "Developing additional problems with your health."
media: {
"type": "html"
"link": "files/Brightcove.com%2FZ678766-1.avi"
}
},
但我需要如下输出:
media: {
"type": "img"
"link": "files/SLP.jpg"
}
items: [
{
"statement": "walking time bomb."
"response": "Developing additional problems with your health."
media: {
"type": "html"
"link": "files/Brightcove.com%2FZ678766-1.avi"
}
},
我需要第一个媒体文件(jpg 格式)像上面一样单独出现在输出中。请帮我解决这个问题。提前致谢
【问题讨论】:
-
根据您的 xslt 和您想要的输出,您的 xml 中的第二个 item 元素应该位于第一个 item 中的 items 元素内。
-
如果你想排除空节点,你需要改变你的选择器。
-
是的@MatthewWhited。我需要第一个媒体元素本身单独出现在 listitem 之前,因为如果我将媒体元素放在 listitem 元素之外,输入的 xml 文件将变得无效。所以只在 listitem 元素内部使用。但我需要像上面那样的预期输出
-
您可以移动媒体类型并链接到根(或项目元素)上的属性。您甚至不需要在 xml 中定义的外部项目元素。请注意,您的 json 无效,因为您缺少属性之间的逗号。