Why does the 'xmlns' attribute affect XPath Node lookup?

霸气de小男生 提交于 2019-12-06 03:26:20

问题


The following code works perfect. See XML file below.

XPathDocument xPathDoc = new XPathDocument(@"C:\Authors.xml");
XPathNavigator navigator = xPathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/Contacts/Author/FirstName");
iterator.MoveNext();
string firstName = iterator.Current.InnerXml;
Console.WriteLine(firstName);

The value of 'firstName' returns 'Joe' which is perfect. However, when I add this attibute xmlns="http://www.w3.org/1999/xhtml" to the '' tag, so that it looks as follows:

<Author xmlns="http://www.w3.org/1999/xhtml">

then the code does not return the correct value ('Joe') Why then the attribute xmlns="http://www.w3.org/1999/xhtml" affects the code above and what am I missing to return the correct value?

Any help will be greatly appreciated.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8" ?> 
<Contacts>
<Author>
<FirstName>Joe</FirstName>
</Author>
<Teacher>
<FirstName>Larry</FirstName>
</Teacher>

<Painter>
<FirstName>Mary</FirstName>
</Painter>
</Contacts>

回答1:


xmlns is namespace which is used to avoid conflict between tags of the xml. Scenario, when one app is using xml from multiple sources and same tagname exist in two or more xml files. Since probablity of such ambiguity is high, namespace is used to reduce it.




回答2:


Your XPath expression is looking for elements "Contacts", "Author" and "FirstName" without namespaces. It looks like the Author element (and any descendant elements which don't have a namespace declaration) do have namespaces, do your XPath expression doesn't match.

To fix it, you'll need to use an XmlNamespaceManager, associate a prefix with the namespace and include that namespace in your XPath expression. Frankly, it gets messy.

Is there any reason you can't use LINQ to XML instead? It makes it much simpler to deal with XML in general and namespaces in particular. I'm happy to come up with a LINQ to XML sample if you're able to use it.

EDIT: Here's some sample LINQ to XML:

XDocument doc = XDocument.Load("authors.xml");
XNamespace ns = "http://www.w3.org/1999/xhtml";
var query = doc.Root
               .Elements(ns + "Author")
               .Elements(ns + "FirstName");
foreach (var element in query)
{
    Console.WriteLine((string) element);
}


来源:https://stackoverflow.com/questions/4728048/why-does-the-xmlns-attribute-affect-xpath-node-lookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!