我需要转换XML并在新节点中使用子节点的值。我尝试过,但是无法获取子节点的值。
这是我要转换的XML
<InvoiceDocument>
<Invoice>
<a>120</a>
<Products>
<Product>
<b>11</b> <!-- Modified by edit -->
</Product>
<Product>
<c>12</c>
</Product>
</Products>
</Invoice>
</InvoiceDocument>
这是必需的输出
<InvoiceDocument>
<d>120</a>
<e>11<b>
<f>12</c>
</InvoiceDocument>
这是我尝试用来获取子节点的值并在另一个节点中使用的代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="InvoiceDocument">
<xsl:apply-templates select="Invoice"/>
<xsl:apply-templates select="Product"/>
</xsl:template>
<xsl:template match="Invoice">
<d><xsl:value-of select="normalize-space(a/text()[1])"/></d>
</xsl:template>
<xsl:template match="Product">
<e><xsl:value-of select="normalize-space(b/text()[1])"/></e>
<f><xsl:value-of select="normalize-space(c/text()[1])"/></f>
</xsl:template>
</xsl:stylesheet>
我尝试了上面的代码,但是无法使用子节点的值。
将您的XSLT样式表更改为以下内容:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*" /> <!-- Removes empty lines -->
<xsl:template match="InvoiceDocument"> <!-- Creates the InvoiceDocument element in the output -->
<xsl:copy>
<xsl:apply-templates select="Invoice"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Invoice"> <!-- Creates the <d> element from the <a> element and descends into the Products/Product nodes -->
<d><xsl:value-of select="normalize-space(a[1])"/></d>
<xsl:apply-templates select="Products/Product" />
</xsl:template>
<xsl:template match="Product/b[1]"> <!-- Creates the <e> element from the first <b> element in Products -->
<e><xsl:value-of select="normalize-space(.)"/></e>
</xsl:template>
<xsl:template match="Product/c[1]"> <!-- Creates the <f> element from the first <c> element in Products -->
<f><xsl:value-of select="normalize-space(.)"/></f>
</xsl:template>
</xsl:stylesheet>
其输出是:
<?xml version="1.0"?>
<InvoiceDocument>
<d>120</d>
<e>11</e>
<f>12</f>
</InvoiceDocument>