我在一个简单的XML文档中设置了我的应用程序,如下所示:
<Settings>
<Server>
<Id>1</Id>
<Name>SRV123456</Name>
<Par Type="Desktop" Region="Western">12</Par>
<Par Type="Laptop" Region="Western">15</Par>
<Par Type="Desktop" Region="Eastern">22</Par>
<Par Type="Laptop" Region="Eastern">25</Par>
<State>WA</State>
</Server>
</Settings>
我正在尝试使用C#和LINQ查询它,使用以下代码:
xelement = XElement.Load(startpath + "\\Settings.xml");
var sn = from sl in xelement.Elements("Server")
where (string)sl.Element("State") == "WA"
where (string)sl.Element("Par").Attribute("Region") == "Western"
where (string)sl.Element("Par").Attribute("Type") == "Desktop"
select sl;
foreach (XElement xele in sn)
{
Console.WriteLine(xele);
Console.WriteLine(xele.Element("Par").Value);
}
这适用于第一个“Par”值,并将返回“12”。但是如果我改变了
where (string)sl.Element("Par").Attribute("Type") == "Desktop"
到
where (string)sl.Element("Par").Attribute("Type") == "Laptop"
它没有返回任何结果......我错过了什么?
答案 0 :(得分:1)
这是一个有效且看起来更漂亮的查询:
var parValue = xdoc.Descendants("Par")
.Where(par=>par.Parent.Element("State")?.Value == "WA")
.Where(par=>par.Attribute("Region")?.Value == "Western")
.Where(par=>par.Attribute("Type")?.Value == "Laptop")
.Select(par=>par.Value)
.FirstOrDefault();
请注意?是一个CS6功能,如果使用CS5,则省略?
,如果需要,检查为空
答案 1 :(得分:0)
我绝不是LINQ的专家
然而
var sn = from sl in xelement.Elements("Server")
where (string)sl.Element("State") == "WA"
where (string)sl.Element("Par").Attribute("Region") == "Western"
where (string)sl.Element("Par").Attribute("Type") == "Desktop"
select sl;
我相信只有返回元素属性(&#34;类型&#34;)==&#34;桌面&#34; 表示仅返回等于&#34;桌面&#34; ...所以当你循环时,结果集中没有
更改为
var sn = from sl in xelement.Elements("Server")
where (string)sl.Element("State") == "WA"
where (string)sl.Element("Par").Attribute("Region") == "Western"
select sl;
它应该返回所有类型......而不仅仅是&#34;桌面&#34;
答案 2 :(得分:0)
也许您正在尝试返回Western / Laptop值= 15?
var state = "WA";
var region = "Western";
var type = "Laptop";
var xElement = XElement.Parse(@"<Settings>
<Server>
<Id>1</Id>
<Name>SRV123456</Name>
<Par Type='Desktop' Region='Western'>12</Par>
<Par Type='Laptop' Region='Western'>15</Par>
<Par Type='Desktop' Region='Eastern'>22</Par>
<Par Type='Laptop' Region='Eastern'>25</Par>
<State>WA</State>
</Server>
</Settings>");
foreach (XElement server in xElement.XPathSelectElements(
String.Format("//Server[State='{0}']", state)))
{
Console.WriteLine(server);
// In your sample the Western/Desktop is the first element
// If you want a specific Par element, you should query again with that filter
foreach (XElement par in server.XPathSelectElements(
String.Format("Par[@Region='{0}' and @Type='{1}']", region, type)))
Console.WriteLine(par.Value); ;
}
我选择XPath over Linq来过滤XML文档,因为XPath对我来说似乎更简洁。