<Products>
<Product ProductID="1">
<productName>Ball</productName>
<Color>Green</Color>
</Product>
<Product ProductID="2">
<productName>Doll</productName>
<Color>White</Color>
</Product>
</Products>
我有一个像上面那样的 xml 输入。但是我在创建产品元素时遇到问题,该产品元素将产品名称作为属性并将产品 ID 作为产品下的元素。下面是我的代码。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="//Products">
<html>
<body>
<Products>
<xsl:for-each select="//Product">
<xsl:call-template name="Import"/>
</xsl:for-each>
</Products>
</body>
</html>
</xsl:template>
<xsl:template name="Import" match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
最佳答案
我相信你可以通过以下方式做到这一点:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="//Products">
<html>
<body>
<Products>
<xsl:apply-templates />
</Products>
</body>
</html>
</xsl:template>
<xsl:template match="Product">
<xsl:element name="product">
<xsl:attribute name="name" select="ProductName/text()" />
<xsl:element name="productID">
<xsl:value-of select="@ProductID" />
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
顺便说一句,您在输入 XML 时有一个小错误(productName
没有大写字母)
关于xml转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13033367/