问题描述
我有一些包含记录和子记录的 XML,如下所示:
I have some XML which contains records and sub records, like this:
<data>
<record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00">
<record jsxid="id0x0b60ff10" string="101"/>
<record jsxid="id0x0e64d8e8" string="63"/>
<record jsxid="id0x2fd83f08" string="Y"/>
</record>
<record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00">
<record jsxid="id0x0b60ff10" string="102"/>
<record jsxid="id0x0e64d8e8" string="77"/>
<record jsxid="id0x2fd83f08" string="Y"/>
</record>
<data>
我需要对其进行转换,以便将子记录的字符串属性作为连续编号的属性带入父记录,然后将其丢弃,如下所示:
I need to transform it so that the string attribute of the sub records are brought up into the parent record as consecutively numbered attributes and then discarded, like this:
<data>
<record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="101" 2="63" 3="Y"/>
<record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="102" 2="77" 3="Y"/>
<data>
子记录的数量在文档中是任意的,但在同一个文档中保持不变.
The number of sub-records is arbitrary across documents but remains static within the same document.
有人会这么好心指出 XSLT 解决方案的方法吗?非常感谢.
Would someone be so kind as to point the way to an XSLT solution? Many thanks.
推荐答案
这是一个完整的解决方案:
Here's a complete solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- By default, recursively copy all nodes unchanged -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<!-- But don't process any children of <record> (such as whitespace)... -->
<xsl:template match="record/node()"/>
<!-- ...except for doubly-nested records;
convert them to attributes, named according to position -->
<xsl:template match="record/record" priority="1">
<xsl:variable name="pos">
<xsl:number/>
</xsl:variable>
<xsl:attribute name="r{$pos}">
<xsl:value-of select="@string"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
请注意,我将您的属性名称更改为r1"、r2"等,因为 XML 不允许您以数字开头.
Note that I changed the name of your attributes to "r1", "r2", etc., because XML doesn't allow you to start a name with a number.
这篇关于使用 XSLT 将子节点移动到父属性中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!