Xpath / C#,从多个名称空间获取数据

时间:2010-10-26 19:24:27

标签: c# xml xpath

因此,在下面的XML中使用此代码示例,我可以成功地从我的XML中获取每个条目的HomeAddress和Name信息。如果我还需要从每个条目中获取ID(驾驶执照号码xxx)信息怎么办?

编辑:更新了XML样本以便澄清

代码示例:

XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(responseFromServer);
        XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xDoc.NameTable);
        xnsmgr.AddNamespace("ns1", "http://www.w3.org/2005/Atom");
        xnsmgr.AddNamespace("ns2", "http://strange.com/ns/1.0/");
        XmlNodeList xnlInsuredListMembers = xDoc.SelectNodes("//ns2:InsuredListMember", xnsmgr);
        foreach (XmlNode xnMember in xnlInsuredListMembers)
        {
            XmlNode xnHomeAddress = xnMember.SelectSingleNode("ns2:HomeAddress", xnsmgr);
            string sHomeAddress = xnHomeAddress.InnerText;

            XmlNode xnName = xnMember.SelectSingleNode("ns2:Name", xnsmgr);
            string sName = xnName.InnerText;

            MessageBox.Show(sHomeAddress + sName);
        }

XML示例

<?xml version="1.0" encoding="UTF-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
      <id>someID</id>
      <title type="text">Title</title>
      <author>
        <name>XML Author</name>
      </author>
      <updated>2010-10-25T20:05:30.267Z</updated>
      <link href="currentURL"></link>
      <link href="nextURL"></link>
      <entry>
        <id>Drivers License Numberxxx</id>
        <content type="application/vnd.ctct+xml">
          <InsuredListMember xmlns="http://strange.com/ns/1.0/">
            <HomeAddress>123 anystreet</HomeAddress>
            <Name>doe, somegal</Name>
          </InsuredListMember>
        </content>
      </entry>
      <entry>
        <id>Drivers License Numberxxx</id>
        <content type="application/vnd.ctct+xml">
          <InsuredListMember xmlns="http://strange.com/ns/1.0/">
            <HomeAddress>321 anystreet</HomeAddress>
            <Name>doe, someguy</Name>
          </InsuredListMember>
        </content>
      </entry>
    </feed>

1 个答案:

答案 0 :(得分:3)

首先,根据您的输入样本,此//ns2:ContactListMember应为//ns2:InsuredListMember

其次,如果上下文节点是某个ns2:InsuredListMember,则此表达式选择id属性:@id

如果您希望给定ns1:id的{​​{1}}子ns1:entry,则此XPath表达式为:ns2:InsuredListMember