我有这份文档,我想在其中获取 "x_server_response/retrieve_resources_by_category_response/source_full_info/record/ datafield[@tag='520']/subfield[@code='a']"
中的值
但我就是做不到!为什么?
我怀疑这与 record 节点的命名空间声明有关。但我不知道该怎么做。
我的代码是这样的:
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']
并完全摆脱目前的两步法。
关于c# - 如何使用 selectsinglenode() 访问具有属性和命名空间的 xml 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716287/