C#XML,找到节点和他的所有父母 [英] C# XML, find node and all his parents

查看:111
本文介绍了C#XML,找到节点和他的所有父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的XML结构:

I got an XML structure like:

<siteNode controller="a" action="b" title="">
  <siteNode controller="aa" action="bb" title="" />
  <siteNode controller="cc" action="dd" title="">
    <siteNode controller="eee" action="fff" title="" />
  </siteNode>
</siteNode>

来自 将C#Linq转换为XML,何时获得父母一个孩子满足条件

我有这样的东西:

XElement doc = XElement.Load("path");
var result = doc.Elements("siteNode").Where(parent =>
  parent.Elements("siteNode").Any(child => child.Attribute("action").Value ==
  ActionName && child.Attribute("controller").Value == ControlerName));

哪个返回我的节点及其父节点.我不仅可以获取节点的父代,还可以获取其祖父母",我的意思是父代的父代等.因此,对于我的XML,它将是:

Which returns my node and its parent. How could I get not only the parent of the node but also its "grandparents", I mean the parent of the parent etc. So with my XML it would be:

<siteNode controller="eee" action="fff" title="" /> 
with parent 
<siteNode controller="cc" action="dd" title="" >
with parent
<siteNode controller="a" action="b" title="" >

一个明显的答案是在找到的父级上使用该linq表达式,直到它为null,但是还有什么更好的(更简洁的)方法吗?

Obvious answer is to use that linq expression on found parent until it's null, but is there any better (cleaner) way?

推荐答案

AncestorsAndSelf方法完全可以满足您的需求,它可以在所有父级上查找元素的祖先. Descendants方法可以按名称查找任何级别的元素,并且FirstOrDefault方法返回符合条件的第一个元素;如果找不到匹配的元素,则返回null:

AncestorsAndSelf method does exactly what you need, it finds ancestors of an element on all parent levels. Descendants method finds elements by name at any level and FirstOrDefault method returns first element that matches criteria or null if no matching element is found:

    XElement el = doc.Descendants("siteNode")
                    .FirstOrDefault(child => 
                        child.Attribute("action").Value == ActionName 
                        && 
                        child.Attribute("controller").Value == ControlerName);
    if (el != null)
    {
        var result2 = el.AncestorsAndSelf();
    }

这篇关于C#XML,找到节点和他的所有父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆