使用xpath查询读取xml中的节点

时间:2014-08-08 20:41:53

标签: xml xpath c#-3.0 xml-namespaces

嗨我有以下代码片段正在工作,当没有可用的命名空间但是如果我使它可用,则它不返回任何值。

xml文件:Person.xml

<?xml version="1.0" encoding="utf-8" ?>
    <Persons>
      <Person name="John Smith">
        <Age>30</Age>
        <Gender>Male</Gender>
      </Person>
      <Person name="Mike Folley">
        <Age>25</Age>
        <Gender>Male</Gender>
      </Person>
      <Person name="Lisa Carter">
        <Age>22</Age>
        <Gender>Female</Gender>
      </Person>
    </Persons>

将上述xml文件加载到xml文档

 string  xmlstr1 = AppDomain.CurrentDomain.BaseDirectory + "Person.xml";
 XmlDocument doc = new XmlDocument();
 doc.Load(xmlstr1);

 XmlNodeList personNodes =  doc.DocumentElement.SelectNodes("Person");

如果我为文档添加命名空间并尝试使用xath获取值,那么它将不起作用。

向root添加名称

  <?xml version="1.0" encoding="utf-8" ?>
        <Persons xmlns="www.google.com">
          <Person name="John Smith">...
          .....

然后我使用以下代码尝试获取值,但没有结果。

XmlNode root = doc.DocumentElement;

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", root.NamespaceURI);

XmlNodeList node = doc.DocumentElement.SelectNodes("Person", nsmgr);

2 个答案:

答案 0 :(得分:1)

命名空间没有前缀,这会增加一些混乱 创建一个具有匹配URI和您自己的前缀的命名空间,然后在查询中使用该前缀。

NameTable nt = new NameTable();
XmlNamespaceManager nsmgr;
nsmgr = new XmlNamespaceManager(nt);

string strURI = "www.google.com"; // the default namespace, must match your doc.
nsmgr.AddNamespace("g", strURI);  // add your own prefix (anything you want really)

// Query with the "g" prefix, that you just defined.
XmlNode ndNode = doc.SelectSingleNode("//g:Person", nsmgr);

答案 1 :(得分:1)

  1. 您在尝试过的XPath中实际上没有使用已注册的前缀

  2. XPath中使用的路径不正确。 <Person>不是根节点,它位于<Person>内。

  3. 这种方式可以让它发挥作用:

    XmlNodeList node = doc.DocumentElement
                          .SelectNodes("/bk:Persons/bk:Person", nsmgr);