且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用selectsinglenode()访问具有属性和名称空间的xml节点

更新时间:2023-11-24 23:20:58

由于部分节点位于"http://www.loc.gov/MARC21/slim/" 命名空间中,但是您的XPath仅在空名称空间中查找元素.

Because part of your nodes are in the "http://www.loc.gov/MARC21/slim/" namespace, but your XPath looks for elements in the empty namespace only.

要解决此问题,请通过调用名称空间管理器使您的环境知道该名称空间:

To fix this, make the namespace known to your environment by invoking a namespace manager:

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']

摆脱现有的分两步走的方法.

and get rid of the two-step approach you currently have altogether.