How to add an XML attribute to an XML file in C #

I am creating an XML file from C # code, but when I add an XML node attribute, I get a problem. Below is the 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> 

The XML attribute does not add "xsi: nil" to the xml file. Please help me with this, where I am wrong.

+4
source share
1 answer

You need to add a schema to your xsi first document

UPDATE you also need to add a 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); 
+5
source

Source: https://habr.com/ru/post/1489067/


All Articles