I want to count the indentation level of a generated XML file. I found some code that could recursively go through the document. But I can't seem to find a way to get the number of indents per element:
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--;
    }
}
The is an example of the XML file:
<?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>
So for example, for the tag <name>Guido</name> the indentation level would be 3.
Could someone help me with this?
                        
The simplest way to get the indentation level of a specific element is to see how many parent levels it has:
int GetDepth(XElement element)
{
    int depth = 0;
    while (element != null)
    {
        depth++;
        element = element.Parent;
    }
    return depth;
}
If you really wanted to do this recursively, you could:
int GetDepth(XElement element)
{
    return element == null ? 0 : GetDepth(element.Parent) + 1;
}
                                
                            
                    See more on this question at Stackoverflow