【问题标题】:How to find out a child's parent?如何找到孩子的父母?
【发布时间】:2012-02-27 13:13:31
【问题描述】:

我正在尝试使用 XElement 找出孩子的父节点。请参见下面的示例。这是我的数据:

<Data>
    <Description>King</Description>
    <Data>
        <Description>Mike</Description>
        <Data id="GUID1" Description="THIS IS A TEST" />
    </Data>
    <Data>
        <Description>David</Description>
        <Data id="GUID2" Description="THIS IS A TEST" />
        <Data id="GUID3" Description="THIS IS A TEST" />
    </Data>
    <Data id="GUID4" Description="THIS IS A TEST" />
</Data>

所以父母(国王)有两个孩子迈克和大卫。我想知道谁是“大卫”的父母,我怎样才能找到这个?

下面是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    var s =
     @"<Data>
           <Description>King</Description>
           <Data>
             <Description>Mike</Description>
             <Data id=""GUID1"" Description=""THIS IS A TEST"" />
           </Data>
           <Data>
             <Description>David</Description>
             <Data id=""GUID2"" Description=""THIS IS A TEST"" />
             <Data id=""GUID3"" Description=""THIS IS A TEST"" />
           </Data>
           <Data id=""GUID4"" Description=""THIS IS A TEST"" />
       </Data>";

    var doc = XElement.Load(new StringReader(s));

    var result = (from data in doc.Descendants("Data")
                  where (string)data.Attribute("id") != null
                  select new
                  {
                      Id = data.Attribute("id").Value,
                      Decription = data.Attribute("Description").Value,
                      Child = data.Parent.Element("Description").Value,
                      Parent = data.Parent.Parent.Value **** THIS LINE ****
                  });

    foreach (var element in result)
    {
        Console.WriteLine("{0} {1}", element.Id, element.Decription);
    }
}

我尝试了一切,但没有运气。我不断得到data.Parent.Parent.Value ="KingMikeDavid" 的全部父级结果,这是错误的。我如何只返回没有孩子的“King”?

【问题讨论】:

    标签: c# xml linq architecture xelement


    【解决方案1】:

    data.Parent.Parent 指的是整个Data 元素,它的值是它的后代的组合值。你需要它的Descriptionchild 的值:

    Parent = data.Parent.Parent == null ? null :
        data.Parent.Parent.Element("Description").Value
    

    【讨论】:

    • 对不起,我忘记在 xml 中添加另一行 请查看更新版本。这会抛出一个空执行??
    • 但是这个元素是最顶层数据元素的子元素,它“属于”国王,可以说,它没有任何父母......我编辑了这个案例的答案.
    【解决方案2】:

    我不确定 LINQ,但如果它不起作用,您可以使用 XPATH 来执行此操作。 http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C 专门看中间的表达式表。你需要这样的表达方式。

    /catalog/cd[last()]   //selects the last cd child of catalog
    

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多