开发者

How do I add a namespace when creating an XML file?

I have to create an XML document in C#.

The root element has to look like this:

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:noNamespaceSc开发者_如何学编程hemaLocation="valuations.xsd">

I'm using the following

XmlElement root = X.CreateElement("valuation-request");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.SetAttribute("xsi:noNamespaceSchemaLocation", "valuations.xsd");

However this produces

<valuation-request 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     noNamespaceSchemaLocation="valuations.xsd"> //missing the xsi:

What am I missing?


Use the overload of SetAttribute, that takes namespace as well:

root.SetAttribute("noNamespaceSchemaLocation", 
    "http://www.w3.org/2001/XMLSchema-instance", 
    "valuations.xsd"
); 


With writer you add it like this:

var writerSettings = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = " ",
            NewLineChars = Environment.NewLine,
            NewLineHandling = NewLineHandling.Replace,
            Encoding = new UTF8Encoding(false)
        };

XmlWriter writer = XmlWriter.Create("C:\test.xml", writerSettings);
writer.WriteStartDocument(false);
writer.WriteStartElement("valuation-request");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "http://www.gzs.si/e-poslovanje/sheme/eSLOG_1-5_EnostavniRacun.xsd");


Recently, I have encountered same issue. To resolve it, I've just add the follow line:

XmlAttribute noNamespaceSchemaLocationAttr = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜