Solve “undeclared prefix” error on XElement.Load()

In order to use a namespace prefix (such as addthis:), the namespace must be declared, by writing xmlns:addthis=”Fixed URI”. This will get added in very first line of your XSLT template. See example below.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <url>
        <loc>https://codeconfig.in/</loc>
        <lastmod>2010-01-20T10:56:47Z</lastmod>
        <changefreq>daily</changefreq>
        <priority>1</priority>
    </url>
    <url>
        <loc>https://codeconfig.in/</loc>
        <lastmod>2009-10-13T10:20:03Z</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.5</priority>
    </url>
    <url>
        <loc>https://codeconfig.in/</loc>
        <lastmod>2009-10-13T10:19:09Z</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.5</priority>
    </url>
</urlset>

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) this error may occur.

Do it by code only:

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", "");  // this line will add namespace
XmlParserContext context = new XmlParserContext(null, xmlns, "", XmlSpace.Default);
XmlReader reader = XmlReader.Create(new StringReader(text), settings, context);
XDocument xmlDoc = XDocument.Load(reader);

And for any additional prefixes add below line more times as required:

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

Leave a Reply

Your email address will not be published. Required fields are marked *