C# 使用特定筛选器加载xml
我有这样的XML格式C# 使用特定筛选器加载xml,c#,vb.net,C#,Vb.net,我有这样的XML格式 <ROOT> <bookstore> <Name>XXXXXX</BUNIT> </bookstore> <book> <ID>000000000000001001</ID> <title>Everyday Italian</title> <author>G
<ROOT>
<bookstore>
<Name>XXXXXX</BUNIT>
</bookstore>
<book>
<ID>000000000000001001</ID>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<ID>000000000000001002</ID>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<ID>000000000000001003</ID>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<ID>000000000000001004</ID>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</ROOT>
但我会给ID的过滤器像下面的代码
_nodeList = objxml.SelectSingleNode("//book/ID['000000000000001001']")
我需要具有该特定ID的完整book节点。如果我正确理解了问题,是否希望通过子元素
ID
值选择book元素
如果是这种情况,您可以使用非常简单的LINQ查询按ID返回book节点(假设您首先更正了XML):
然后,您可以将值投影到匿名类型,并将查询强制转换到列表以枚举结果:
var book = (from n in xml.Descendants("ROOT").Elements("book")
where n.Element("ID").Value == "000000000000001001"
select new
{
ID = (string)n.Element("ID").Value,
Title = (string)n.Element("title").Value,
Author = (string)n.Element("author").Value,
Year = (string)n.Element("year").Value,
Price = (string)n.Element("price").Value
}).ToList();
这将产生如下输出:
var book = onjxml.SelectSingleNode("//ROOT/book[ID='000000000000001003']")
您的XML中有一个错误,您没有关闭
,还有什么
?这XXXXXX
是一个问题。+1但是,您不需要双斜杠的根。
var book = (from n in xml.Descendants("ROOT").Elements("book")
where n.Element("ID").Value == "000000000000001001"
select new
{
ID = (string)n.Element("ID").Value,
Title = (string)n.Element("title").Value,
Author = (string)n.Element("author").Value,
Year = (string)n.Element("year").Value,
Price = (string)n.Element("price").Value
}).ToList();
var book = onjxml.SelectSingleNode("//ROOT/book[ID='000000000000001003']")