SolutionCottage.com
Posted  30 Oct 2008 - 12:57:41

Category: XML


SelectNodes and SelectSingleNode breaks w. no namespace

Issue:
You might find SelectNodes or SelectSingleNode not working when you have no namespace on your XmlNodes. I found this issue when creating a sitemap to use with Google. They require a format where you have no namespace set on the sitemap node. Please see this url for information:

https://www.google.com/webmasters/tools/docs/en/protocol.html#sitemapIndexXMLExample

Solution:
Let's say you have an XMLDocument with Xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.google.com/schemas/sitemap/0.84">
<sitemap>
<loc>http://localhost/sitemap.xml</loc>
<lastmod>2008-10-30T12:34:54+00:00</lastmod>
</sitemap>
</sitemapindex>

If you search this Xml like this:

Dim subNode As System.Xml.XmlNode = xDocument.SelectSingleNode("//sitemap/lastmod")


You will not find anything (or at least I didn't with my build up XML using XmlNodes). You can solve it like this:

nsmgr.AddNamespace("ab", "http://www.google.com/schemas/sitemap/0.84")
Dim subNode As System.Xml.XmlNode = xDocument.SelectNodes("//ab:sitemap/ab:lastmod", nsmgr)


The string ("http://www.google.com/schemas/sitemap/0.84") should be set to the same as the parent namespace. In my Xml you can see I have this set on the sitemapindex element.



Marked as helpful by 3 users




0 comments:








© SolutionCottage 2008-2011 9/24/2017 1:15:02 PM