我正在尝试使用 XslCompiledTransform C# 类将一个 xml 文件转换为另一个。但是,命名空间第二次包含在我的一个元素(SerialNum)中。我究竟做错了什么?
这是我的 C# 代码:
// Create a reader to read books.xml
XmlReader reader = XmlReader.Create("machine1.xml");
// Create a writer for writing the transformed file.
XmlWriter writer = XmlWriter.Create("machine2.xml");
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("transform.xsl");
// Execute the transformation.
transform.Transform(reader, writer);
这是我的 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>