Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
If you XML source publishes invalid XML for some reason ( i.e. it has Xml elements referring to undeclared namespace ) and you try to load this XML in XMLDocument. You would end up getting exception similar to <NameSpace> is an undeclared namespace.
eg:
<?xml version="1.0" encoding="utf-16"?>
<root> <Name xsi:nil="true">name1</Name> <Name xsi:nil="true">name2</Name> <Name xsi:nil="true">name3</Name> </root>
Ideally this is an Invalid XML but there is a way to load it in XMLDocument using following code snippet.
XmlDocument doc = new XmlDocument();
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("xsi", "https://www.w3.org/2001/XMLSchema-instance");
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlReaderSettings xset = new XmlReaderSettings();
xset.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader rd = XmlReader.Create(new StringReader(XMLSource), xset, context);
doc.Load(rd);
Runeet Vashisht
Comments
Anonymous
October 17, 2012
This is awesome, exactly what I need. I knew I had to somehow inject a declaration into the nametable, but it wasn't obvious how to do that when I was trying to use the LoadXml() method. Thakyou very much!Anonymous
October 28, 2014
Thank you for a quick fix to and obvious issue