2016-02-25 193 views
3

我愿意接受所有建议,但如果可能,不要循环。我想从这个XML到一个变量的NUM发现的属性,但它回来NULL,我想不通为什么:C#和XPath - 获取属性?

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]"); 

回答

1

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

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); 
-1

这似乎工作:

XDocument xdoc = XDocument.Parse(xmlStringGoesHere); 
int num = Int32.Parse(xdoc.Root.Elements().Where(p => p.Name.LocalName == "orcid-search-results").Attributes().Where(a => a.Name.LocalName == "num-found").First<XAttribute>().Value);