繁体   English   中英

获取特定节点的xml属性值

[英]Fetch xml attribute value for a specific node

<root>
 <A testId ="test">
    <B  id="ABC">one
    </B>
    <B id="ZYZ">two
    </B>
    <B  id="QWE">three
    </B>
    <B>four
    </B>
  </A>
</root>

需要为节点<A>提取testId属性值。我正在使用以下c#代码,但它会抛出null异常。

doc.XPathSelectElement("//A/@testId")

任何帮助表示赞赏!

您无法使用XPath获取属性(实际上, XPathSelectElement方法使用名称表示状态,其目的是选择元素)。 因此,您应该选择element,然后获取其属性(假设您正在使用Linq to XML。如果不是,我建议您开始这样做):

(string)doc.XPathSelectElement("//A").Attribute("testId")

在这种情况下,实际上使用XPath没有任何好处:

(string)doc.Root.Element("A").Attribute("testId")

假设您有xml文件XMLFile1.xml,然后尝试以下代码,它将给您结果test

 XDocument xDoc = XDocument.Load("XMLFile1.xml");
 var test = xDoc.Root.Element("A").Attribute("testId").Value;

更新:-

正如谢尔盖(Sergey)所建议的那样,使用铸造比访问Value属性更安全,因此如下更新代码

var test = (string)xDoc.Root.Element("A").Attribute("testId");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM