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文档中,我想遍历所有<blist:books>
元素。 (即) 如何处理名称空间?Linq to XML - 命名空间
我试图
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)不返回任何结果。
答
这里有两个不同的问题。
- 你调用
Elements
方法,它返回调用它的元素的直接子元素。由于<html>
元素没有直接<blist:books>
子元素,您没有得到任何结果。 - XML区分大小写。您需要编写
books
,而不是Books
。
另外,写作from el in whatever select el
没有意义。除非您添加逻辑(例如where
或orderby
子句或非重要的select
),否则应该只写whatever
。
因此,你需要用下面的更换你的LINQ查询:
IEnumerable<XElement> titleElement = element.Descendants(blist + "books");
是的,它解决DMY problem.Thank你。 – David 2010-01-28 15:26:19
如果我想使用XmlTextReader(不是LINQ到XML),我怎么能达到相同的结果? – David 2010-01-28 15:31:05
这将需要更多的代码。 LINQ to XML是在.NET中处理XML的最简单方式。 – SLaks 2010-01-28 15:34:44