嗨,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
如果需要使用您描述的"每代码一行"文件格式,那么在XSLT1中解析代码有点棘手。它在XSLT2中相对简单。只需包含文件并使用tokenize
函数:
注意:如果代码中有标记字符,如<
和&
,则需要对它们进行转义。
<!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>
XSLT1中的字符串标记很难看,但如果您将代码列表格式化为XML,那么就不必这样做了
您的代码格式如下:
<codes>
<code>textX</code>
<code>text2</code>
<code>text1</code>
<code>text3</code>
</codes>
您可以在XSLT1:中运行排序
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/root">
<xsl:copy>
<xsl:variable name="root" select="."/>
<xsl:for-each select="document('sort.xml')/codes/code">
<xsl:copy-of select="$root/node[@code=current()]"/>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>