简体   繁体   English

在c#中从xml获取属性值

[英]Getting Attribute's value from xml in c#

I have a LINQ expression which gets the XML attribute values from a xml file. 我有一个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;

And the xml file is: 而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>

I am only getting the attribute result (value) for first element of 1500. If I search same thing for 18 it doesn't return any result and no exception. 我只获得1500的第一个元素的属性result(value)。如果我搜索18的相同的东西,它不会返回任何结果,也没有异常。 Any help appreciated....Plz help!!! 任何帮助表示赞赏.... Plz帮助!!!

You should be more granular, call sub Descendants with Store (XName): 您应该更精细,使用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;

Because now you're retrieving only the first Store of each Group which is 1500 . 因为现在你仅检索第一 Store每个Group1500

Try this out:- 试试这个: -

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

Yes, you have a little error in your code: You are splitting your xml into group-elements (you have just one group). 是的,您的代码中有一点错误:您将xml拆分为group-elements(您只有一个组)。 Then you check if the first store element has the value 1500 (you are not checking if the following store elements have maybe the value 1500) 然后检查第一个store元素是否具有值1500(您没有检查以下存储元素是否具有值1500)

You need to change your code into the following 您需要将代码更改为以下内容

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM