-->

XML WriteAttributeString error

2019-06-24 15:15发布

问题:

When I write this entry here:

<XmlRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:nsSBAK" xsi:schemaLocation ="urn:nsSBAK SBAK.xsd"> 

with this code:

xmlWriter.WriteStartElement("XmlRoot");
xmlWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
xmlWriter.WriteAttributeString("xmlns", null, null, "urn:nsSBAK");
xmlWriter.WriteAttributeString("schemaLocation", null, "urn:nsSBAK SBAK.xsd");

I get debug error:

The prefix '' cannot be redefined from '' to 'urn:nsSBAK' within the same start element tag.

Can you help me ?

回答1:

You need to define the namespace of the element on the WriteStartElement itself. Also noticed you did not add the namespace to your schemaLocation. wich you dit in your desired result. Also added that for you in my example:

xmlWriter.WriteStartElement("XmlRoot", "urn:nsSBAK");
xmlWriter.WriteAttributeString("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "urn:nsSBAK SBAK.xsd");


标签: c# xml xmlwriter