FOLLOW US
4dots Software CODE BLOG

How to ignore Namespace when selecting XML nodes with XPath

Normally, if an XML Document has namespaces defined it is necessary to use a namespace manager in order to process this document and select XML nodes with XPath.
This is very inconvenient.
If you just want to select XML nodes ignoring their namespace there is a way to do it.
In order to do this, you have to select using "[local-name() = 'XML_NODE_NAME']" where XML_NODE_NAME is the name of the xml node you want to select.

If for example we have the following XML sitemap and we want to get the loc nodes that contain the URLs of the sitemap, then we have to do the folllowing :



<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="gss.xsl"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url><loc>http://www.4dots-software.com/</loc><lastmod>2017-04-02T04:52:19+00:00</lastmod><changefreq>weekly</changefreq><priority>1.00</priority></url>
<url><loc>http://www.4dots-software.com/images/l_2.jpg</loc><lastmod>2014-11-27T09:06:52+00:00</lastmod><changefreq>monthly</changefreq><priority>0.50</priority></url>
<url><loc>http://www.4dots-software.com/images/l_1.jpg</loc><lastmod>2014-11-27T09:06:52+00:00</lastmod><changefreq>monthly</changefreq><priority>0.50</priority></url>
<url><loc>http://www.4dots-software.com/images/icon_twitter-sm.png</loc><lastmod>2014-11-27T09:07:18+00:00</lastmod><changefreq>monthly</changefreq><priority>0.50</priority></url>
<url><loc>http://www.4dots-software.com/images/go.png</loc><lastmod>2014-11-27T09:07:18+00:00</lastmod><changefreq>monthly</changefreq><priority>0.50</priority></url>
</urlset>

	
 
	string txt = System.IO.File.ReadAllText("c:\docuemnts\sitemap.xml");

	System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
	doc.LoadXml(txt);
						
	System.Xml.XmlNodeList nolos = doc.SelectNodes("//*[local-name() = 'loc']");

	for (int k = 0; k < nolos.Count; k++)
	{
		AddURL(nolos[k].InnerText);
	}
	

 

Please Donate!

Please Share!