[英]Getting Attribute's value from xml in c#
我有一个LINQ表达式,它从xml文件中获取XML属性值。
var xml = XElement.Load(@"C:\\StoreServer1.xml");
var query = from e in xml.Descendants("Groups")
where int.Parse(e.Element("Store").Value) == 1500
select e.Element("Store").Attribute("WeekDayStClose").Value;
而xml文件是:
enter<?xml version="1.0" encoding="utf-8" ?>
<Stores>
<Groups Range="000">
<Store WeekDayStClose="210" SatStClose="21" SunStClose="22">1500</Store>
<Store WeekDayStClose="23" SatStClose="24" SunStClose="25">18</Store>
<Store WeekDayStClose="23" SatStClose="24" SunStClose="25">19</Store>
</Groups>
</Stores>
我只获得1500的第一个元素的属性result(value)。如果我搜索18的相同的东西,它不会返回任何结果,也没有异常。 任何帮助表示赞赏.... Plz帮助!!!
您应该更精细,使用Store
(XName)调用子Descendants
:
var xml = XElement.Load(@"C:\\New Folder\\StoreServer1.xml");
var query = from e in xml.Descendants("Groups").Descendants("Store")
where int.Parse(e.Value) == 18
select e.Attribute("WeekDayStClose").Value;
因为现在你仅检索第一 Store
每个Group
是1500
。
var xml = XElement.Load(@"C:\\StoreServer1.xml");
var query = xml.Descendants("Groups").Descendants("Store").Where(e => int.Parse(e.Value) == 18).Select(e=> e.Attribute("WeekDayStClose").Value);
是的,您的代码中有一点错误:您将xml拆分为group-elements(您只有一个组)。 然后检查第一个store元素是否具有值1500(您没有检查以下存储元素是否具有值1500)
您需要将代码更改为以下内容
var query = from e in xml.Descendants("Store")
where int.Parse(e.Value) == 1500
select e.Attribute("WeekDayStClose").Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.