使用LINQ to XML,方法获取路径,所有的树叶? [英] Using Linq To XML, method to get path to all leaves?

查看:228
本文介绍了使用LINQ to XML,方法获取路径,所有的树叶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有以下XML树



<预类=郎咸平的XML prettyprint-覆盖> <根>
< A>
< A1,GT;
<&A1A GT; 1000℃; / A1A>
<&A1B GT; 2000< / A1B>
<&A1C GT; 3000 LT; / A1C>
< / A1>
< A2>
<&A2A GT; 4000< / A2A>
<&A2B GT; 5000< / A2B>
< / A2>
< / A>
< B>
< B1>
<&B1A GT; 6000< / B1A>
< / B1>
< / B>
< /根>

这是一个方法接受一个XDocument我想制作一本字典,其中的关键是路径(一个真正的XPath的)和值来自于相应的叶值。

 根/ A / A1 / A1A 1000 
根/ A / A1 / A1B 2000
根/ A / A1 / A1C 3000
根/ A / A2 / A2A 4000
根/ A / A2 / A2B 5000
根/ b / B1 / B1A 6000

看似简单Linq中做XML,但我不能换我。头周围


解决方案

您可以找到通过查找元素的叶子有没有后代:

  VAR DOC = XDocument.Load(文件名); 
无功叶=
从E在doc.Descendants()
,其中e.Elements()任何()
选择e!。



我不知道是否有一个内置的方式来获得一个元素的路径,但是你可以很容易地创建一个扩展方法来构建它:

 静态类扩展
{
公共静态字符串路径(这的XElement元素)
{
的XElement TMP =元素;
路径字符串=的String.Empty;
,而(TMP!= NULL)
{
路径=/+ tmp.Name +路径;
TMP = tmp.Parent;
}
返回路径;
}
}

您可以再建字典是这样的:

  VAR字典= leaves.ToDictionary(E => e.Path(),E => e.Value); 


Ok, I've got the following XML tree

<root>
    <A>
        <A1>
            <A1A>1000</A1A>
            <A1B>2000</A1B>
            <A1C>3000</A1C>
        </A1>
        <A2>
            <A2A>4000</A2A>
            <A2B>5000</A2B>
        </A2>
    </A>
    <B>
        <B1>
            <B1A>6000</B1A>
        </B1>
    </B>
</root>

From a method receiving an XDocument I want to produce a dictionary where the key is the path (really an XPath) and the value comes from the value in the corresponding leaf.

root/A/A1/A1A    1000
root/A/A1/A1B    2000
root/A/A1/A1C    3000
root/A/A2/A2A    4000
root/A/A2/A2B    5000
root/B/B1/B1A    6000

Seems simple to do in Linq to XML but I can't wrap my head around it.

解决方案

You can find the leaves by looking for elements that have no descendants:

var doc = XDocument.Load(fileName);
var leaves = 
    from e in doc.Descendants()
    where !e.Elements().Any()
    select e;

I don't know if there is a built-in way to get the path of an element, but you can easily create an extension method to build it:

static class Extensions
{
    public static string Path(this XElement element)
    {
        XElement tmp = element;
        string path = string.Empty;
        while (tmp != null)
        {
            path = "/" + tmp.Name + path;
            tmp = tmp.Parent;
        }
        return path;
    }
}

You can then build the dictionary like this:

var dict = leaves.ToDictionary(e => e.Path(), e => e.Value);

这篇关于使用LINQ to XML,方法获取路径,所有的树叶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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