使用Xelement从xml获取值

时间:2014-07-11 06:19:43

标签: xml linq

我试图从类名为“ECMInstruction”的实体元素中获取属性“Id”的值,但不返回任何内容。

    <?xml version="1.0" encoding="utf-8"?>
    <Root>
      <Class Name="ECMInstruction" Style="Top">
        <Entity Id="1" Name="DocumentInformation" />
      </Class>
      <Class Name="dfgfggfdg" Style="Top">
        <Entity Id="1" Name="dfgfgfdgd" />
      </Class>
    </Root>

  private void dcLisT_SelectedIndexChanged(object sender, EventArgs e)
    {
       String curItem = dcList.SelectedItem.ToString();

       IEnumerable<String> lList =
         from el in doc.Descendants("Entity")
         where el.ElementsBeforeSelf("Class") && Attribute("Name").Value == curItem
         select (String)el.Attribute("Id").Value;

       EntityList.Items.AddRange(lList.ToArray());
    }

2 个答案:

答案 0 :(得分:0)

你可以这样做:

IEnumerable<String> lList = from el in doc.Descendants("Class")
                            where el.Attribute("Name").Value == curItem
                            select el.Element("Entity").Attribute("Id").Value;

答案 1 :(得分:0)

它会起作用:

        var lList = from a in xd.Descendants("Root").Elements("Class")
                    where a.Attribute("Name").Value == curItem
                    select a.Element("Entity").Attribute("Id").Value;