XmlCompiledTransform重复名称空间替换元素的值
问题描述:
我试图使用XslCompiledTransform C#类将一个xml文件转换为另一个。然而,这个命名空间在我的一个元素(SerialNum)中被第二次包含。我究竟做错了什么?XmlCompiledTransform重复名称空间替换元素的值
这里是我的C#代码:
这里是我的XSL:
<xsl:stylesheet version="1.0" xmlns:cm="http://schemas.datacontract.org/2004/07/CMachines"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<!-- Copy everything not subject to the exceptions below -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<!-- Ignore the disabled element -->
<xsl:template match="cd:Disabled" />
<!-- Reset the value of the serial num element to 0 -->
<xsl:template match="cm:SerialNum">
<SerialNum>0</SerialNum>
</xsl:template>
</xsl:stylesheet>
输入:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMachine xmlns="http://schemas.datacontract.org/2004/07/CMachines" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Machine>
<Name>DellM7600</Name>
<ID>1</ID>
<Type>Laptop</Type>
<Disabled>false</Disabled>
<SerialNum>47280420</SerialNum>
</Machine>
<Machine>
<Name>DellD600</Name>
<ID>2</ID>
<Type>Laptop</Type>
<Disabled>false</Disabled>
<SerialNum>53338123</SerialNum>
</Machine>
</ArrayOfMachine>
输出:
<?xml version="1.0" encoding="utf-8"?><ArrayOfMachine xmlns="http://schemas.datacontract.org/2004/07/CMachines" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Machine>
<Name>DellM7600</Name>
<ID>1</ID>
<Type>Laptop</Type>
<SerialNum xmlns="" xmlns:cm="http://schemas.datacontract.org/2004/07/CMachines">0</SerialNum>
</Machine>
<Machine>
<Name>DellD600</Name>
<ID>2</ID>
<Type>Laptop</Type>
<SerialNum xmlns="" xmlns:cm="http://schemas.datacontract.org/2004/07/CMachines">0</SerialNum>
</Machine>
</ArrayOfMachine>
所需的输出:
<?xml version="1.0" encoding="utf-8"?><ArrayOfMachine xmlns="http://schemas.datacontract.org/2004/07/CMachines" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Machine>
<Name>DellM7600</Name>
<ID>1</ID>
<Type>Laptop</Type>
<SerialNum>0</SerialNum>
</Machine>
<Machine>
<Name>DellD600</Name>
<ID>2</ID>
<Type>Laptop</Type>
<SerialNum>0</SerialNum>
</Machine>
</ArrayOfMachine>
答
只需更换:
<xsl:template match="cm:SerialNum">
<SerialNum>0</SerialNum>
</xsl:template>
有:
<xsl:template match="cm:SerialNum">
<xsl:copy>0</xsl:copy>
</xsl:template>
什么你现在正在创建中没有命名空间新SerialNum
元素 - 不像原始的,它继承了它父母的名字空间。这就是为什么你看到xmlns=""
声明:它显示该元素是在没有名字空间,不像其父。
xmlns:cm="http://schemas.datacontract.org/2004/07/CMachines"
只是从xsl:stylesheet
祖先继承而来。您可以通过将exclude-result-prefixes="cm"
属性添加到xsl:stylesheet
元素中来消除它 - 但仅仅将原始SerialNum
元素复制为其原始名称空间并且没有从样式表中继承即可更简单。
您可能在这里有答案,请检查http://*.com/a/10173482/920557。 –