zoukankan      html  css  js  c++  java
  • Using Xpath With Default XML Namespace in C#

    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:Tempooks.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:Tempooks.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:Tempooks.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

  • 相关阅读:
    月薪3万+的大数据人都在疯学Flink,为什么?
    Flink应用场景
    Flink生态与未来
    flink学习笔记-split & select(拆分流)
    .NET MVC5简介(四)Filter和AuthorizeAttribute权限验证
    .NET MVC5简介(三)Result
    .NET MVC5简介(二)
    VUE基础实用技巧
    .NET MVC5简介(一)
    WebApi简介
  • 原文地址:https://www.cnblogs.com/3Tai/p/10482683.html
Copyright © 2011-2022 走看看