创建XML文件时如何添加命名空间?

10

我需要在C#中创建一个XML文档。

根元素应该长这样:

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

我正在使用以下代码:

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

然而,这会产生

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

我漏掉了什么?

3个回答

8
使用重载 SetAttribute 方法,并同时传递命名空间参数:
root.SetAttribute("noNamespaceSchemaLocation", 
    "http://www.w3.org/2001/XMLSchema-instance", 
    "valuations.xsd"
); 

我正在使用root.SetAttribute("xsi:noNamespaceSchemaLocation", "valuations.xsd");。你认为它应该是什么样子? - Steven
1
尝试使用此代码:root.SetAttribute("noNamespaceSchemaLocation", "valuations.xsd","http://www.w3.org/2001/XMLSchema-instance"); - Mubashir Khan
返回 <valuation-request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" d1p1:noNamespaceSchemaLocation="http://www.w3.org/2001/XMLSchema-instance" xmlns:d1p1="valuations.xsd"> - Steven
我将它们交换以看起来像 root.SetAttribute("noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "valuations.xsd") …bish bash bosh..干杯 - Steven

0

最近,我遇到了同样的问题。为了解决它,我只需添加以下行:

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

这在我的代码上运行得非常好。对我来说,XMLSchema-instance 部分很重要。 - user4628051

0

使用writer,您可以这样添加:

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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接