如何在C#中的XML文件中添加XML属性

use*_*287 4 c# xml

我正在从C#代码生成XML文件,但是当我向XML节点添加属性时,我遇到了问题.以下是代码.

XmlDocument doc = new XmlDocument();
XmlNode docRoot = doc.CreateElement("eConnect");
doc.AppendChild(docRoot);
XmlNode eConnectProcessInfo = doc.CreateElement("eConnectProcessInfo");
XmlAttribute xsiNil = doc.CreateAttribute("xsi:nil");
xsiNil.Value = "true";
eConnectProcessInfo.Attributes.Append(xsiNil);
docRoot.AppendChild(eConnectProcessInfo);
Run Code Online (Sandbox Code Playgroud)

结果:

<eConnect>
    <eConnectProcessInfo nil="true"/>
</eConnect>
Run Code Online (Sandbox Code Playgroud)

预期结果:

<eConnect>
    <eConnectProcessInfo xsi:nil="true"/>
</eConnect>
Run Code Online (Sandbox Code Playgroud)

XML属性未在xml文件中添加"xsi:nil".我帮我这个,我错了.

Bob*_*ale 6

您需要先为xsi将模式添加到文档中

更新您还需要将命名空间作为属性添加到根对象

//Store the namespaces to save retyping it.
string xsi = "http://www.w3.org/2001/XMLSchema-instance";
string xsd = "http://www.w3.org/2001/XMLSchema";
XmlDocument doc = new XmlDocument();
XmlSchema schema = new XmlSchema();
schema.Namespaces.Add("xsi", xsi);
schema.Namespaces.Add("xsd", xsd);
doc.Schemas.Add(schema);
XmlElement docRoot = doc.CreateElement("eConnect");
docRoot.SetAttribute("xmlns:xsi",xsi);
docRoot.SetAttribute("xmlns:xsd",xsd);
doc.AppendChild(docRoot);
XmlNode eConnectProcessInfo = doc.CreateElement("eConnectProcessInfo");
XmlAttribute xsiNil = doc.CreateAttribute("nil",xsi);
xsiNil.Value = "true";
eConnectProcessInfo.Attributes.Append(xsiNil);
docRoot.AppendChild(eConnectProcessInfo);
Run Code Online (Sandbox Code Playgroud)