gpt4 book ai didi

C# 和 XPath - 获取属性?

转载 作者:数据小太阳 更新时间:2023-10-29 02:44:21 24 4
gpt4 key购买 nike

我对所有建议持开放态度,但如果可能的话,我不喜欢循环。我试图从这个 XML 中获取 num-found 属性到一个变量中,但它返回 NULL,我不知道为什么:

xmlStringGoesHere 下面是这个: enter image description here代码:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStringGoesHere);
int intNumFound = Convert.ToInt32(xmlDoc.SelectSingleNode("/orcid-message/orcid-search-results/@num-found").Value);

我想使用 SelectSingleNode,因为它只有一行代码。有人建议在下面这样做,但这些都不起作用。此外,有没有一种方法可以避免所有“本地名称”废话使代码膨胀?

object intNumFound = xmlDoc.SelectSingleNode("/*[local-name() = 'orcid-message']/*[local-name() = 'orcid-search-results']");
object intNumFound = xmlDoc.SelectSingleNode("/*[local-name() = 'orcid-message']/*[local-name() = 'orcid-search-results']/@num-found]");

最佳答案

问题是没有名为orcid-messageorcid-search-results 的元素; XML 中的 xmlns 使得您必须限定这些名称。以下是在查询中包含 namespace 的方法:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStringGoesHere);

var nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsMgr.AddNamespace("o", "http://www.orcid.org/ns/orcid");

var attribute = xmlDoc.SelectSingleNode(
"/o:orcid-message/o:orcid-search-results/@num-found",
nsMgr);
int intNumFound = Convert.ToInt32(attribute.Value);

关于C# 和 XPath - 获取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640593/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com