[英]Sort nodes in XML using XSLT
I have an XSL variable matchedNodes
which holds XML data. 我有一个XSL变量
matchedNodes
,它保存XML数据。 Which means 意思是
<xsl:copy-of select="$matchedNodes"/>
will produce an XML like this 将产生这样的XML
<home name="f">
<standardpage>
<id text="a1"></id>
</standardpage>
<searfchpage>
<id text="a2"></id>
</searfchpage>
<searfchpage>
<id text="a3"></id>
</searfchpage>
</home>
I want to sort this XML so that searfchpage
nodes always comes first..Is there any way to do this? 我想对这个XML进行排序,以便
searfchpage
节点始终排在第一位。有什么办法可以做到这一点吗?
Simple ordering (move <searfchpage>
to the top, keep the rest of the children in orignal order): 简单的排序(将
<searfchpage>
移动到顶部,让其余的孩子按照原始顺序):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="home">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates select="searfchpage" />
<xsl:apply-templates select="*[not(self::searfchpage)]" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
complex ordering (lets you define any arbitrary order, either dynamically via a param or statically via a hard-coded string): 复杂排序(允许您通过参数动态或通过硬编码字符串静态定义任意顺序):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="sortOrder" select="'searfchpage,standardpage,otherpage'" />
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="home">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:apply-templates select="*">
<xsl:sort select="string-length(
substring-before(concat($sortOrder, ',', name()), name())
)" />
<xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Try this, 尝试这个,
Input: 输入:
<home name="f">
<standardpage>
<id text="a1"></id>
</standardpage>
<searfchpage>
<id text="a2"></id>
</searfchpage>
<searfchpage>
<id text="a3"></id>
</searfchpage>
</home>
XSL: XSL:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
</xsl:apply-templates>
<xsl:apply-templates select="node()">
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Output 产量
<home name="f">
<searfchpage>
<id text="a2"/>
</searfchpage>
<searfchpage>
<id text="a3"/>
</searfchpage>
<standardpage>
<id text="a1"/>
</standardpage>
</home>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.