using System; using System.IO; using System.Xml; using System.Xml.XPath; namespace consAppXpath1 { class Program { static void Main(string[] args) { //load xml Byte[] content = System.Text.Encoding.ASCII.GetBytes(Properties.Resources.TestConfigInNamespace); MemoryStream memoryStream = new MemoryStream(content); XPathDocument doc = new XPathDocument(memoryStream); //setup xpath processing XPathNavigator nav = doc.CreateNavigator(); NameTable nt = new NameTable(); XmlNamespaceManager xnmgr1 = new XmlNamespaceManager(nt); XmlNamespaceManager xnmgr2 = new XmlNamespaceManager(nt); xnmgr1.AddNamespace("x", nav.NamespaceURI); xnmgr2.AddNamespace("a", "http://www.adatum.com"); XPathNodeIterator ni = nav.Select("/a:Tests/a:Test/a:CommandLine", xnmgr2); string result = (ni.Count > 0) ? "selection exists" : "no selection"; Console.WriteLine(result); foreach (var item in ni) { Console.WriteLine("command line is {0}", item); } Console.ReadKey(); } } }
So, when processing XML in .NET, you must address the namespace question, whether it is default or null or even multiple namespaces within one xml document, otherwise, you will fall short of getting what you are after. Whether that be XPath or even LINQ to XML, so get familiar with the XmlNameSpaceManager object, you will be glad you did.