具有所有属性的linq-to-xml查询
本文关键字:linq-to-xml 查询 属性 | 更新日期: 2023-09-27 18:03:29
我有一个类似的xml
文档
<Products>
<Product Name="Mobile Device" Code="10000000000000000006">
<Providers>
<Provider Name="VODA" Code="VODA">
<Menus>
<Menu Name="Home" Url="TopModelsNew.aspx" DisplayOrder="1" NewWindow="0"/>
<Menu Name="Top Queries" Url="TopIssues.aspx" DisplayOrder="2" NewWindow="0"/>
<Menu Name="Error Codes" Url="PCErrors.aspx" DisplayOrder="3" NewWindow="0"/>
</Menus>
</Provider>
</Providers>
</Product>
我想在列表中找到产品代码="10000000000000000006"和提供商代码="VODA"的所有菜单
结果应该是
名称Url取消播放顺序主页TopModels 0
我正在尝试linq到xml,如下所示
XDocument xdoc = XDocument.Load(Server.MapPath("~/App_Data/LeftMenu.xml"));
var products = from product in xdoc.Descendants("Product") where
new{
.....
};
我找不到如何得到这份名单。
XDocument xdoc = XDocument.Load(Server.MapPath("~/App_Data/LeftMenu.xml"));
var menus = from product in xdoc.Descendants("Product")
where (string)product.Attribute("Code") == "10000000000000000006"
from provider in product.Descendants("Provider")
where (string)provider.Attribute("Code") == "VODA"
from menu in provider.Descendants("Menu")
select new {
Name = (string)menu.Attribute("Name"),
Url = (string)menu.Attribute("Url"),
DisplayOrder = (int)menu.Attribute("DisplayOrder")
};
结果:
Name Url DisaplayOrder
"Home" "TopModelsNew.aspx" 1
"Top Queries" "TopIssues.aspx" 2
"Error Codes" "PCErrors.aspx" 3
var menus = doc.Root
.Elements("Product")
.Where(p => (string)p.Attribute("Code") == "10000000000000000006")
.SelectMany(p => p.Element("Providers").Elements("Provider"))
.Where(p => (string)p.Attribute("Code") == "VODA")
.SelectMany(p => p.Element("Menus").Elements("Menu"))
.ToList();
它返回样本数据的所有3个菜单元素。您可以使用投影来获取匿名对象,而不是XElement
:
var menus = doc.Root
.Elements("Product")
.Where(p => (string)p.Attribute("Code") == "10000000000000000006")
.SelectMany(p => p.Element("Providers").Elements("Provider"))
.Where(p => (string)p.Attribute("Code") == "VODA")
.SelectMany(p => p.Element("Menus").Elements("Menu"))
.Select(m => new {
Name = (string)m.Attribute("Name"),
Url = (string)m.Attribute("Url"),
DisplayOrder = (int)m.Attribute("DisplayOrder")
})
XDocument xdoc = XDocument.Load(Server.MapPath("~/App_Data/LeftMenu.xml"));
var menus = xdoc.Descendants("Menu").Where(x =>
x.Ancestors("Product").First().Attribute("Code").Value == "10000000000000000006" &&
x.Ancestors("Provider").First().Attribute("Code").Value == "VODA");
对源XML文档进行一些假设:
<Menu>
节点必须且仅具有一个<Product>
祖先节点<Menu>
节点必须且仅具有一个<Provider>
祖先节点