Linq to XML - 命名空间
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Book List</title>
</head>
<body>
<blist:books
xmlns:blist="http://www.wrox.com/books/xml">
<blist:book>
<blist:title>XSLT Programmers Reference</blist:title>
<blist:author>Michael Kay</blist:author>
</blist:book>
</blist:books>
</body>
</html>
从给定的 Xml 文档中,我想迭代所有
元素。
(IE) 我如何处理命名空间?
我尝试过
XNamespace blist = XNamespace.Get("http://www.wrox.com/books/xml");
XElement element = XElement.Load("Books.xml");
IEnumerable<XElement> titleElement =
from el in element.Elements(blist + "books") select el;
,但枚举(titleElement)没有返回任何结果。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Book List</title>
</head>
<body>
<blist:books
xmlns:blist="http://www.wrox.com/books/xml">
<blist:book>
<blist:title>XSLT Programmers Reference</blist:title>
<blist:author>Michael Kay</blist:author>
</blist:book>
</blist:books>
</body>
</html>
from the given Xml document,I want to iterate all <blist:books>
elements.
(i.e)
How to i handle the namespace ?
i tried
XNamespace blist = XNamespace.Get("http://www.wrox.com/books/xml");
XElement element = XElement.Load("Books.xml");
IEnumerable<XElement> titleElement =
from el in element.Elements(blist + "books") select el;
but the enumeration (titleElement) does not return any result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你在这里有两个不同的问题。
Elements
方法,该方法返回您调用该方法的元素的直接子元素。由于元素没有 direct
子元素,因此您不会获得任何结果。书籍
,而不是书籍
。另外,在任何 select el 中编写
from el
是没有意义的。除非您放置加法逻辑(例如where
或orderby
子句,或不平凡的select
),否则您应该只编写不管怎样。
因此,您需要将 LINQ 查询替换为以下内容:
You have two different problems here.
Elements
method, which returns the direct child elements of the element you call it on. Since the<html>
element has no direct<blist:books>
child elements, you aren't getting any results.books
, notBooks
.Also, there's no point in writing
from el in whatever select el
. Unless you put addition logic (such as awhere
ororderby
clause, or a non-trivialselect
), you should just writewhatever
.Therefore, you need to replace your LINQ query with the following: