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.

2

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

3 Comments

This is not giving result: My expected result is ::: <eConnect xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema"> <SOPTransactionType> <eConnectProcessInfo xsi:nil="true" /> <taRequesterTrxDisabler_Items xsi:nil="true" /> <taUpdateCreateItemRcd xsi:nil="true" /> </SOPTransactionType> </eConnect>
@user2493287 Please see updated answer, I forgot to include the line that adds the xmlns attribute. I'm also slapping in the xsd namespace you want
@user2493287 My answer doesn't include it, but your comment indicates that you need to create the SOPTransactionType> element before you add the eConnectProcessInfo
2

Below is the simplest way to append an xsi:nil="true" element:

XmlNode element = null;
XmlAttribute xsinil = doc.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
xsinil.Value = "true";
element.Attributes.Append(xsinil);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.