Linq to xml查询返回无结果

时间:2013-06-28 01:57:53

标签: linq-to-xml linqpad

我有以下xml数据:

<?xml version="1.0" encoding="utf-8" ?>
  <root>
    <object name="Object01" table="Table01" pk="Table01_Id">
      <table name="Table02" pk="Table02_Id" fk="Table01_Id" include="false">
        <table name="Table03" pk="Table03_Id" fk="Table02_Id" include="true">
          <table name="Table04" pk="Table04_Id" fk="Table03_Id" include="true">
          </table>
        </table>
      </table>
      <table name="Table05" pk="Table05_Id" fk="Table01_Id" include="false">
      <table name="Table06" pk="Table06_Id" fk="Table05_Id" include="true" />
      </table>
    </object>
    <object name="Object02" table="Table07" pk="Table07_Id">
      <table name="Table08" pk="Table08_Id" fk="Table07_Id" include="false">
        <table name="Table04" pk="Table04_Id" fk="Table08_Id" include="true" />
      </table>    
    </object>
  </root>

当我在LinqPad中运行以下内容时:

    var root = XElement.Load("D:\\Foxpert\\FlagChanges\\FlagChanges\\Modified.xml");
    var table = root.Descendants("table").Where(e => e.Attribute("name").Value == "Table04")
    .Select(e => new XElement(e.Parent)).First();
table.Dump();
     var obj = root.Descendants("object").Where(o => o.Attribute("name").Value == "Object01")
    .Select(o => new XElement(o)).First();
     obj.Dump();
     foreach (XElement t in obj.Descendants("table")){
    t.Attribute("name").Dump();
    t.Parent.Attribute("name").Dump();
}
     table.Attribute("name").Dump();
     var parent = obj.Descendants("table")
    .Where(e => e.Attribute("name")==table.Attribute("name"))
    .Select(e => new XElement(e.Parent));
     parent.Dump();

父结果为空。

有人可以尝试LinqPad中的代码并告诉我为什么我的父母是空的吗?

1 个答案:

答案 0 :(得分:1)

 var parent = obj.Descendants("table")
.Where(e => e.Attribute("name").Value==table.Attribute("name").Value)
.Select(e => new XElement(e.Parent));

e.Attribute("name")table.Attribute("name")不是“平等” - 它们只是具有相同的值。