Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-计数缩进级别XML_C#_Xml_Count_Indentation - Fatal编程技术网

C#-计数缩进级别XML

C#-计数缩进级别XML,c#,xml,count,indentation,C#,Xml,Count,Indentation,我想计算生成的XML文件的缩进级别。我发现了一些可以递归遍历文档的代码。但我似乎找不到一种方法来获得每个元素的缩进数: void Process(XElement element, int depth) { // For simplicity, argument validation not performed if (!element.HasElements) { // element is child with no descendants

我想计算生成的XML文件的缩进级别。我发现了一些可以递归遍历文档的代码。但我似乎找不到一种方法来获得每个元素的缩进数:

void Process(XElement element, int depth)
{
    // For simplicity, argument validation not performed

    if (!element.HasElements)
    {
        // element is child with no descendants
    }
    else
    {
        // element is parent with children

        depth++;

        foreach (var child in element.Elements())
        {
            Process(child, depth);
        }

        depth--;
    }
}
以下是XML文件的一个示例:

<?xml version="1.0" encoding="UTF-8"?>
<data name="data_resource" howabout="no">
    <persons>
        <person>
            <name>Jack</name>
            <age>22</age>
            <pob>New York</pob>
        </person>
        <person>
            <name>Guido</name>
            <age>21</age>
            <pob>Hollywood</pob>
        </person>
        <person>
            <name surname="Bats">Michael</name>
            <age>20</age>
            <pob>Boston</pob>
        </person>
    </persons>
    <computers>
        <computer>
            <name>My-Computer-1</name>
            <test>
                <test2>
                    <test3>
                        <test4 testAttr="This is an attribute" y="68" x="132">
                            Hatseflatsen!
                        </test4>
                    </test3>
                </test2>
            </test>
        </computer>
    </computers>
</data>

杰克
22
纽约
圭多
21
好莱坞
迈克尔
20
波士顿
My-Computer-1
哈塞弗拉森!
例如,对于标记
Guido
,缩进级别将为3


有人能帮我吗?

获取特定元素缩进级别的最简单方法是查看它有多少父级:

int GetDepth(XElement element)
{
    int depth = 0;
    while (element != null)
    {
        depth++;
        element = element.Parent;
    }
    return depth;
}
如果您真的想递归地执行此操作,您可以:

int GetDepth(XElement element)
{
    return element == null ? 0 : GetDepth(element.Parent) + 1;
}

获取特定元素缩进级别的最简单方法是查看它有多少父级:

int GetDepth(XElement element)
{
    int depth = 0;
    while (element != null)
    {
        depth++;
        element = element.Parent;
    }
    return depth;
}
如果您真的想递归地执行此操作,您可以:

int GetDepth(XElement element)
{
    return element == null ? 0 : GetDepth(element.Parent) + 1;
}

正是我要找的!谢谢:这正是我想要的!谢谢:D