开发者

Xpath/C#, getting data from multiple namespaces

开发者 https://www.devze.com 2023-01-22 06:29 出处:网络
So, in the XML below using this code sample, i can successfully grab HomeAddress and Name information for each entry from my XML. What if I also need to grab the ID (drivers license numberxxx) informa

So, in the XML below using this code sample, i can successfully grab HomeAddress and Name information for each entry from my XML. What if I also need to grab the ID (drivers license numberxxx) information from each entry?

EDIT: Updated XML sample for clarificaiton

Code Sample:

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 Sample

<?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>


First, this //ns2:ContactListMember should be //ns2:InsuredListMember according to your input sample.

Second, if the context node is some ns2:InsuredListMember, the the id attribute is selected by this expresion: @id.

If you want the ns1:id child of ns1:entry for the given ns2:InsuredListMember, this XPath expression: ../../ns1:id

0

精彩评论

暂无评论...
验证码 换一张
取 消