If you have a XML file without any prefix in the namespace:

<bookstore xmlns="http://www.contoso.com/books"></bookstore>

you have this workaround:

XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
// ignore the namespace as there is a single default namespace:
reader.Namespaces = false;
XPathDocument document = new XPathDocument(reader);
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("//book");

If you have a XML file with a prefix in the namespace:

<bookstore xmlns:ns="http://www.contoso.com/books"></bookstore>

Use this:

XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
XPathDocument document = new XPathDocument(reader);
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("//book");

Of course, you can use a namespace manage if needed:

XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
XPathDocument document = new XPathDocument(reader);
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(reader.NameTable);
nsmgr.AddNamespace("ns", "http://www.contoso.com/book");
XPathNodeIterator nodes = navigator.Select("//book", nsmgr);

I think that it's the easiest way to make the code working in the most cases.

原文地址:https://stackoverflow.com/questions/585812/using-xpath-with-default-namespace-in-c-sharp/54128951#54128951

相关文章:

  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-14
  • 2022-01-17
猜你喜欢
  • 2021-05-26
  • 2022-12-23
  • 2021-06-18
  • 2021-12-23
  • 2022-12-23
  • 2021-11-12
  • 2022-12-23
相关资源
相似解决方案