如何过滤XML文件中的属性值?

时间:2012-05-11 02:24:40

标签: c# linq-to-xml

考虑以下xml文件

<?xml version="1.0" encoding="utf-8"?>
<RootElement>
  <HomeSite>
    <Context enabled="1" active="1">
      <Culture>en-us</Culture>
      <Affiliate>0</Affiliate>
      <EmailAddress>sreetest@test.com</EmailAddress>
      <Password>sreesree1</Password>
    </Context>
  <Context enabled="0" active="1">
      <Culture>en-us</Culture>
      <Affiliate>0</Affiliate>
      <EmailAddress>sreetest@test.com</EmailAddress>
      <Password>sreesree1</Password>
    </Context>
  </HomeSite>
</RootElement>

目前我在做

string applicationType="HomeSite";
    XDocument xmlSkuDescDoc = null;
    xmlSkuDescDoc = XDocument.Load(@"D:\Config.xml");
    var newContextElementCollection = new List<ContextElements>();
     //get the property and values
    (from data in xmlSkuDescDoc.Descendants(applicationType)
     select data)
     .Descendants("Context")
     .Elements()
     .ToList()
     .ForEach(i => newContextElementCollection.Add(new ContextElements { Property = i.Name.ToString(), Value = i.Value }));

哪里

public class ContextElements
{
    public string Property { get; set; }
    public string Value { get; set; }
}

现在我需要为那些属性值为 enabled =“1”的上下文提取记录。

那怎么办呢?

需要帮助。

1 个答案:

答案 0 :(得分:2)

这个怎么样:

xmlSkuDescDoc.Descendants("Context")
                .Where(el => el.Attribute("enabled").Value == "1")
                .Elements()
                .ToList()
                .ForEach(i => newContextElementCollection.Add(new ContextElements { Property = i.Name.ToString(), Value = i.Value }));