通过XSLT设置XML属性的顺序? [英] Setting the order of XML attributes via XSLT?
问题描述
我使用XSLT解析XML格式的HTML。我的HTML看起来像这样:
< html>
< head>
< meta charset =utf-8/>
< title>测试< /标题>
< / head>
< body>
< img height =width ='src =google.gif?<>/>
< / body>
< / html>
在XSLT解析后,它看起来像这样:
<$ p
< html>
< head>
< meta charset =utf-8/>
< title>测试< / title> ;
< / head>
< body>
< img height =src =google.gif?<>width =/>
< / body>
< / html>
我想< code>< img height =width =src =google.gif?<>/> code>,但默认情况下,属性按字母顺序排序,我无法使用
< xsl:sort>
。
输入HTML (附带信息):
< html>
< head>
< meta charset =utf-8/>
< title> Test< / title>
< / head>
< body>
< img height =13width =12src =google.gif? ID = ID1/>
< / body>
< / html>
XSLT:
< xsl:stylesheet version =1.0xmlns: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 =img>
< xsl:copy>
< xsl:sort select =name()/>
< xsl:attribute name ={name()}>
< xsl:value-of select =。/>
< / xsl:attribute>
< / xsl:for-each>
< xsl:apply-templates />
< / xsl:copy>
< / xsl:template>
< / xsl:stylesheet>
结果:
< HTML>
< head>
< meta charset =utf-8/>
< title>测试< /标题>
< / head>
< body>
< img height =13id =id1width =12src =google.gif?/>
< / body>
< / html>
I have HTML in XML format which I am parsing using XSLT. My HTML looks like this:
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<img height="" width="' src="google.gif?<>" />
</body>
</html>
After XSLT parsing it looks like this:
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<img height="" src="google.gif?<>" width=""/>
</body>
</html>
I want @src
as last attribute like <img height="" width="" src="google.gif?<>" />
, but by default attributes are sorted in alphabetical order. I am not able to do it using <xsl:sort>
.
Input HTML (with wellformation):
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<img height="13" width="12" src="google.gif?" id="id1"/>
</body>
</html>
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
<xsl:template match="img">
<xsl:copy>
<xsl:for-each select="@*[not(name()='src')]">
<xsl:sort select="name()"/>
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates select="@*[name()='src']"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Result:
<html>
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<body>
<img height="13" id="id1" width="12" src="google.gif?"/>
</body>
</html>
这篇关于通过XSLT设置XML属性的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!