Workaround for "undeclared prefix" error on XElement.Load()

This XML is not valid.

In order to use a namespace prefix (such as addthis:), the namespace must be declared, by writing xmlns:addthis="some URI".

In general, you shouldn't parse HTML using an XML parser, since HTML is likely to be invalid XML, for this reason and a number of other reasons (undeclared entities, unescaped JS, unclosed tags).
Instead, use HTML Agility Pack.


If you need to do it all in code what you want is something like this:

    XmlReaderSettings settings = new XmlReaderSettings { NameTable = new NameTable() };
    XmlNamespaceManager xmlns = new XmlNamespaceManager(settings.NameTable);
    xmlns.AddNamespace("addthis", "");
    XmlParserContext context = new XmlParserContext(null, xmlns, "", XmlSpace.Default);
    XmlReader reader = XmlReader.Create(new StringReader(text), settings, context);
    xmlDoc.Load(reader);

And for any additional prefixes add more of these:

    xmlns.AddNamespace("prefix", "");

Tags:

Xml

Xelement