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.
You need to add the schema to your document for xsi first
UPDATE you also need to add the namespace as an attribute to the root object
//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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With