我正在尝试使用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();
我做错了什么?
由于
约翰
答案 0 :(得分:7)
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")
答案 1 :(得分:3)
您应该将默认命名空间传递给WriteStartElement方法。
答案 2 :(得分:0)
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名称表中注册。稍后在http://www.w3.org/2001/XMLSchema-instance
方法中使用ns
参数XmlWriter
将在xsi
之前添加XML名称空间前缀。
XML名称空间xsi
的URI也可以通过常量System.Xml.Schema.XmlSchema.InstanceNamespace
在.NET中获得。