Undeclared Namespace in XML (eg: xsi is an undeclared namespace)

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.


<?xml version=”1.0″ encoding=”utf-16″?>
<Name xsi:nil=“true”>name1</Name>
<Name xsi:nil=“true”>name2</Name>
<Name xsi:nil=“true”>name3</Name>

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”, “http://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);

Runeet Vashisht

Comments (2)

  1. 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!

  2. Geoff says:

    Thank you for a quick fix to and obvious issue