C#XML-带有XML编写器的多命名空间声明

本文关键字:命名空间 声明 带有 XML C#XML- | 更新日期: 2023-09-27 18:12:39

我试图在C#中使用System.XML.Xmlwriter创建一个具有多个命名空间的XML文档,在编译时收到以下错误:

前缀"无法从"重新定义为"http://www.acme.com/BOF'位于相同的起始元素标记内。

我的全部代码如下:

        XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
        XmlWriter writer = XmlWriter.Create("C:''ACME''xml.xml", settings);
        writer.WriteStartDocument();
        writer.WriteStartElement("BOF");
        writer.WriteAttributeString("xmlns", null, null, "http://www.acme.com/BOF");  //This is where I get my error
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("fileName", null, null, "test.xml");
        writer.WriteAttributeString("date", null, null, "2011-10-25");
        writer.WriteAttributeString("origin", null, null, "MYORIGIN");
        writer.WriteAttributeString("ref", null, null, "XX_88888");
        writer.WriteEndElement();
        writer.WriteStartElement("CustomerNo");
        writer.WriteString("12345");
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        writer.Close();

我做错了什么?

感谢

John

C#XML-带有XML编写器的多命名空间声明

writer.WriteStartElement("BOF"); // write element name BOF, no prefix, namespace ""
writer.WriteAttributeString("xmlns", null, null, "http://www.acme.com/BOF");  //Set namespace for no prefix to "http://www.acme.com/BOF".

第二行没有任何意义,因为您正在将默认(无前缀(名称空间分配给与其本身不同的其他名称空间。

writer.WriteStartElement("BOF", "http://www.acme.com/BOF") 替换这两行

您应该将默认命名空间传递给WriteStartElement方法。

writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

应写成

writer.WriteAttributeString("xsi", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema-instance");

在这种情况下,前缀xsi被注册在XML名称表中。稍后以XmlWriter的方法将http://www.w3.org/2001/XMLSchema-instance用于参数ns将预加xsi的XML命名空间前缀。

XML命名空间xsi的URI在.NET中也可用常量System.Xml.Schema.XmlSchema.InstanceNamespace