开发者

Linq to XML - Namespaces

<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.


You have two different problems here.

  1. You're calling the 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.
  2. XML is case sensitive. You need to write books, not Books.

Also, there's no point in writing from el in whatever select el. Unless you put addition logic (such as a where or orderby clause, or a non-trivial select), you should just write whatever.

Therefore, you need to replace your LINQ query with the following:

IEnumerable<XElement> titleElement = element.Descendants(blist + "books");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜