2013-12-23 44 views
0

我有一个LINQ表达式,它从xml文件中获取XML属性值。从xml中获取属性值c#

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第一个元素属性的结果(值),如果我搜索同样的事情18不返回任何结果也不例外。任何帮助赞赏.... Plz的帮助!

回答

1

尝试了这一点: -

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); 
+0

这帮助。非常感谢。我犯的错误是什么......我做了什么? – prasuangelo

+0

因为'Element'获得第一个(按文档顺序)具有指定XName的子元素,所以你使用了'e.Element(“Store”)'而不是'Descendants(“Store”)'。(来源:MSDN) – erdinger

1

你应该更细化,调用子DescendantsStore(的XName):

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; 

因为现在你只检索每个Group这是1500第一Store

0

是的,你有你的代码一点点错误: 要拆分的XML转换成组元素(你只有一组)。然后,你检查的第一家专卖店元素的值是1500(你不检查,如果下列存储单元具有也许值1500)

你需要改变你的代码如下

 var query = from e in xml.Descendants("Store") 
        where int.Parse(e.Value) == 1500 
        select e.Attribute("WeekDayStClose").Value; 
+0

只有1个'商店' –

+0

我的错误,我的意思是写“商店” –