解析 XDocument 的属性
我尝试解析这样的 XML 文件:
<books>
<book>
<attr name="Moby Dick">Moby Dick is a classic</attr>
<attr isbn="isbnNumber">123456789</attr>
</book>
</books>
How can I get the value of "123456789"?我真的不需要第一个属性。
我尝试在获取 XElements 的 foreach 循环中读取这些内容,但我不断收到 NULL 对象异常。
foreach(XElement xe in XDoc.Attribute("attr"))
{
string str = xe.Attribute("isbnNumber").Value // NULL EXCEPTION HERE
}
提前致谢...
I have tried to parse an XML file like this:
<books>
<book>
<attr name="Moby Dick">Moby Dick is a classic</attr>
<attr isbn="isbnNumber">123456789</attr>
</book>
</books>
How can I get the value of "123456789"? I don't really need the first attribute.
I tried reading these in a foreach loop getting XElements but I keep getting a NULL object exception.
foreach(XElement xe in XDoc.Attribute("attr"))
{
string str = xe.Attribute("isbnNumber").Value // NULL EXCEPTION HERE
}
Thanks in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试使用
XPathSelectElement()
扩展方法 [您需要使用 System.Xml.XPath 来获取它们]。例如
PS。一个好的 XPath 测试器位于:http://www. Yetanotherchris.me/home/2010/6/7/online-xpath-tester.html
You could try using the
XPathSelectElement()
extension method [you'll need to use System.Xml.XPath to get them].E.g.
PS. A good XPath tester is at: http://www.yetanotherchris.me/home/2010/6/7/online-xpath-tester.html
123456789实际上是一个元素的值,而不是一个属性。您可以像这样完成您想要的操作:
您甚至可以将其写成一行,但如果您是 LINQ to XML 的新手,这可能会更容易阅读。
123456789 is actually the value of an element, not an attribute. What you want can be done like so:
You could even make it one line but this might be easier to read if you're new to LINQ to XML.
好吧,我不知道如何回应个人答案......但我实现了它们,并且它们都有效。
我同意 Reddog 的答案,因为它更简单一些,而且对于 LINQ 来说,它是目前最容易阅读的。
感谢您的回复!
Well, I can't figure out how to respond to the individual answers..... but I implemented them both and they both work.
I am going with Reddog's answer as it is a little more straightforward and being new to LINQ it is the easiest as of now for readability.
Thanks for the responses!