我想要格式如下的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<ac:Main xmlns:trip="http://www.test.com/main.xsd"
xmlns:abc="http://www.test.com/Types.xsd"
xmlns:tw="http://www.test.com/TW.xsd"
xmlns:ck="http://www.test.com/CK.xsd"
xmlns:k1="http://www.test.com/K1.xsd"
xmlns:d1="http://www.test.com/D1.xsd"
xmlns:ac="http://www.test.com/Ac.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.test.com/Ac.xsd file:/D:/schema/AC.xsd">
<ac:Records>
<d1:Header>
<abc:FirstElement>firstValue</abc:FirstElement>
</d1:Header>
</ac:Records>
</ac:Main>
因此,我使用 XmlWriter 编写了如下代码:
using (XmlWriter writer = XmlWriter.Create(path, settings))
{
writer.WriteStartElement("ac", "Main", "xmlns");
writer.WriteAttributeString("xmlns", "trip", null, http://www.test.com/main.xsd");
writer.WriteAttributeString("xmlns", "abc", null, http://www.test.com/Types.xsd");
writer.WriteAttributeString("xmlns", "tw", null, http://www.test.com/TW.xsd");
writer.WriteAttributeString("xmlns", "kc", null, "http://www.test.com/CK.xsd");
writer.WriteAttributeString("xmlns", "k1", null, "http://localhost:8080/K1.xsd");
writer.WriteAttributeString("xmlns", "d1", null, "http://localhost:8080/D1.xsd");
writer.WriteAttributeString("xsi","schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "http://www.test.com/Ac.xsd file:/D:/schema/AC.xsd");
// writer.WriteAttributeString("xmlns", "ac", null, "http://www.test.com/Ac.xsd ");
writer.WriteStartElement("ac", "Records", "xmlns");
writer.WriteStartElement("d1", "Header", "xmlns");
writer.WriteStartElement("abc", "FirstElement", "xmlns");
writer.WriteString("firstValue");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
但取消注释行 writer.WriteAttributeString("xmlns", "ac", null, "http://www.test.com/Ac.xsd "); 产生错误“前缀 'ac' 不能在同一起始元素标记内从 'xmlns' 重新定义为 'http://www.test.com/Ac.xsd'。”
因此,我如上面的代码所示注释了该行,我得到的输出为:
<?xml version="1.0" encoding="utf-8"?>
<ac:Main
xmlns:wctrp="http://www.test.com/main.xsd"
xmlns:abc="http://www.test.com/Types.xsd"
xmlns:tw="http://www.test.com/TW.xsd"
xmlns:ck="http://www.test.com/CK.xsd"
xmlns:k1="http://www.test.com/K1.xsd"
xmlns:d1="http://www.test.com/D1.xsd"
xmlns:ac="http://www.test.com/Ac.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.test.com/Ac.xsd file:/D:/schema/AC.xsd"
xmlns:ac="xmlns">
<ac:Records>
<d1:Header xmlns:hd1="xmlns">
<abc:FirstElement xmlns:iaiabc="xmlns">firstValue</abc:FirstElement>
</d1:Header>
</ac:Records>
</ac:Main>
不需要的属性是元素 'Main' 中的 xmlns:ac="xmlns"、'd1:Header' 中的 xmlns:hd1="xmlns" 和
'abc:FirstElement' 中的 xmlns:iaiabc="xmlns"。
任何人都好心地建议我应该怎么做才能删除不需要的属性并以最高格式获得输出。
我是 XmlWriter 的新手。