给定 .xml 文件的结构、名称和值未知。
对于每个具有简单结构(没有子节点,没有属性,但有文本且不为空)的非根元素,将其转换为父级的属性。
我有 .xml 文件:
<list>
<worker>
<name atr="ss">val1</name>
</worker>
<worker>
<make1>val2</make1>
</worker>
<worker>
<name>
<make2>val3</make2>
</name>
</worker>
<worker>
<name>
<doo atr="ss1">val4</doo>
<make3></make3>
</name>
</worker>
</list>
我想得到这个:
<list>
<worker>
<name atr="ss">val1</name>
</worker>
<worker make1="val2"/>
<worker>
<name make2="val3"/>
</worker>
<worker>
<name>
<doo atr="ss1">val4</doo>
<make3/>
</name>
</worker>
</list>
这是我现在的 .xsl(无法正常工作):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes" method="xml"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//*[not(*|@*)]">
<xsl:copy>
<xsl:attribute name="{name()}">
<xsl:value-of select="text()"/>
</xsl:attribute>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
怎么样:
XSL 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="*[not(*|@*)]" mode="attribute"/>
<xsl:apply-templates select="*[*|@*] | text()" />
</xsl:copy>
</xsl:template>
<xsl:template match="*" mode="attribute">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
请记住,属性必须在子元素之前创建。
为响应要求的变化而添加:
在某些时候,条件的数量足以证明只将它们写入一次,并通过根据集合差异(即非交集)定义“其他”节点集来避免在否定中重复它们:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:variable name="my-set" select="*[text() and not(*|@*)]" />
<xsl:apply-templates select="$my-set" mode="attribute"/>
<xsl:apply-templates select="node()[not(count(.|$my-set) = count($my-set)]" />
</xsl:copy>
</xsl:template>
<xsl:template match="*" mode="attribute">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)