Gui*_*ser 1 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
}
else
{
// element is parent with children
depth++;
foreach (var child in element.Elements())
{
Process(child, depth);
}
depth--;
}
}
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
因此,例如,对于标记<name>Guido</name>,缩进级别将为3.
有人可以帮我吗?
获取特定元素的缩进级别的最简单方法是查看它具有多少父级别:
int GetDepth(XElement element)
{
int depth = 0;
while (element != null)
{
depth++;
element = element.Parent;
}
return depth;
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想以递归方式做到这一点,你可以:
int GetDepth(XElement element)
{
return element == null ? 0 : GetDepth(element.Parent) + 1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |