我必须在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:
我错过了什么?
答案 0 :(得分:8)
使用SetAttribute的重载,它也会占用命名空间:
root.SetAttribute("noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance",
"valuations.xsd"
);
答案 1 :(得分:1)
最近,我遇到了同样的问题。要解决它,我只需添加以下行:
XmlAttribute noNamespaceSchemaLocationAttr = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
答案 2 :(得分:0)
使用编写器,您可以这样添加:
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");