I have a bunch of C# classes, which are auto generated from an XSD. Then I generate XML files based on those C# classes. Nothing existing so far.
The proble
As expected there is no solution for that case out of the box, so I improvise a bit and achieved my goal in a post processing logic.
I am parsing the generated XML and if I am looking for a node with xsi:nil attribute, but without NV attribute - I add NV attribute with default value. Same for the nodes with NV attribute, but no xsi:nil.
Here is the code:
XmlDocument doc = new XmlDocument();// instantiate XmlDocument and load XML from file doc.Load("somepath.xml"); //Get the nodes with NV attribute(using XPath) and add xsi:nill to that nodes XmlNodeList nodes = doc.SelectNodes("//*[@NV]"); foreach (XmlNode node in nodes) { XmlAttribute nilAttr = doc.CreateAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"); nilAttr.Value = "true"; node.Attributes.Append(nilAttr); } //Get the nodes with xsi:nill attribute(using XPath) and add NV with default value to that nodes XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); XmlNodeList nilNodes = doc.SelectNodes("//*[@xsi:nil]", nsManager); foreach (XmlNode node in nilNodes) { XmlAttribute nvAttr = doc.CreateAttribute("NV"); nvAttr.Value = "7701003"; node.Attributes.Append(nvAttr); } doc.Save("somepath.xml");
The upper answer makes totally sense, but since these classes are auto-generated I will do it my way with the post processing, cause if the provider changes the XSD schema, my solution doesn't need any extra work. Thanks anyway.