5

I am generating XML file from C# code but when I add attribute to XML node I am getting problem. Following is code.

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

Result:

<eConnect>
    <eConnectProcessInfo nil="true"/>
</eConnect>

Expected Result:

<eConnect>
    <eConnectProcessInfo xsi:nil="true"/>
</eConnect>

XML attribute is not adding "xsi:nil" in xml file. Please help me for this, where I am going wrong.

4

2 回答 2

8

您需要先将架构添加到 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);
于 2013-07-01T10:39:33.987 回答
2

以下是附加xsi:nil="true"元素的最简单方法:

XmlNode element = null;
XmlAttribute xsinil = doc.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
xsinil.Value = "true";
element.Attributes.Append(xsinil);
于 2019-12-24T14:45:03.570 回答