簡體   English   中英

如何使用selectsinglenode()訪問具有屬性和名稱空間的xml節點

[英]How to access a xml node with attributes and namespace using selectsinglenode()

我在此文檔中想要獲取"x_server_response/retrieve_resources_by_category_response/source_full_info/record/ datafield[@tag='520']/subfield[@code='a']"但我只是做不到! 為什么?

我懷疑這與記錄節點上的名稱空間聲明有關。 但是我不知道該怎么做。

我的代碼如下所示:

XmlNodeList xmlResources = r.ResponseXmlDocument.SelectNodes("x_server_response/retrieve_resources_by_category_response/source_full_info);              

            foreach (XmlNode xmlResource in xmlResources)   
            {
                string information = xmlResource.SelectSingleNode("record/datafield[@tag='520']/subfield[@code='a']").InnerText;   

xml如下所示:

 <x_server_response> metalib_version="4.00 (20)>
    <source_full_info> 
      <record xmlns="http://www.loc.gov/MARC21/slim/" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="http://www.loc.gov/MARC21/slim 
      http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> 
      <controlfield tag="001">CKB02166</controlfield> 
                <datafield tag="520" ind1=" " ind2=" "> 
        <subfield code="a">Providing access to thousands of online journals from leading 
        scholarly, academic and business publishers, the Ingenta Select service provides fast and 
        reliable access from a global network of servers to users' desktops around the world. 
        ## ##Ingenta Select provides access to more than 5,000 electronic 
        publications from over 190 publisher clients and bring together an extensive range of services 
        for the librarian and end-user alike</subfield> 
      </datafield>          </record> 
      </source_full_info> 
      <session_id new_session="N">3B7F9EQE259KNK1YUK462VCCG4455T4BUPUC5B9LVQS9XD16U6</session_id>
<x_server_response> 

因為部分節點位於"http://www.loc.gov/MARC21/slim/"名稱空間中,但是您的XPath僅在空名稱空間中查找元素。

要解決此問題,請通過調用名稱空間管理器使您的環境知道該名稱空間:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(r.ResponseXmlDocument);
nsmgr.AddNamespace("marc", "http://www.loc.gov/MARC21/slim/");
string xpath = "marc:record/marc:datafield[@tag='520']/marc:subfield[@code='a']";

// ...
string information = xmlResource.SelectSingleNode(xpath).InnerText;

編輯:雖然選擇可能更容易

//marc:datafield[@tag='520']/marc:subfield[@code='a']

並擺脫您目前共有的兩步走方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM