Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add XML attribute in XML file in C#

Tags:

c#

xml

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.

like image 619
user2493287 Avatar asked Jul 01 '13 10:07

user2493287


1 Answers

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);
like image 167
Bob Vale Avatar answered Sep 18 '22 11:09

Bob Vale