嗨,所有StackOverFlowers,
我偶然发现了一个无法解决的大问题,试图对XML进行排序。我有如下所示的XML数据集;
<root>
<node code="text1"> ... </node>
<node code="text2"> ... </node>
<node code="text3"> ... </node>
<node code="textX"> ... </node>
</root>
现在,我想按代码属性对其进行排序,并希望存储在外部文件SORT.XML中排序的代码属性列表。代码属性将被排序并保存在SORT.XML中,如下所示(一行,一个属性);
textX
text2
text1
text3
...等等...
处理后,OUTPUT.XML看起来像
<root>
<node code="textX"> ... </node>
<node code="text2"> ... </node>
<node code="text1"> ... </node>
<node code="text3"> ... </node>
</root>
我真的很困,并且不知道如何使用XSLT继续/解决这个问题?
感谢您的所有帮助!
DeLuka
答案 0 :(得分:0)
如果需要使用您所描述的“每个代码一行”的文件格式,则在XSLT 1中解析代码会有些棘手。在XSLT 2中相对简单。只需添加文件并使用{{ 1}}函数:
注意:如果您的代码中有tokenize
和<
之类的标记字符,则需要对它们进行转义。
&
XSLT 1中的标记字符串很丑陋,但是如果将代码列表格式化为XML,则不必这么做。
您的代码格式如下:
<!DOCTYPE xsl:stylesheet [
<!ENTITY codes SYSTEM "sort.txt">
]>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sort="urn:sort">
<!-- Include the ordered list of codes. -->
<sort:order>&codes;</sort:order>
<!-- This key is used to select the nodes to output -->
<xsl:key name="node-key" match="node" use="@code"/>
<xsl:template match="/root">
<xsl:copy>
<xsl:variable name="root" select="."/>
<!-- For each code in the list, output the nodes with matching code attributes -->
<xsl:for-each select="tokenize(document('')/*/sort:order, '\s+')">
<xsl:copy-of select="key('node-key', ., $root)"/>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
您可以在XSLT 1中运行排序:
<codes>
<code>textX</code>
<code>text2</code>
<code>text1</code>
<code>text3</code>
</codes>