且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#的xml中计算每个节点中的子节点和元素的数量

更新时间:2023-11-24 15:46:58

使用.NET中提供的XML类之一解析文件,例如 https://msdn.microsoft.com/ en-us / library / system.xml.xmldocument(v = vs.110).aspx [ ^ ]。


看看例子:

 //定义xml文档内容
string xcontent = @<? xml version =' 1.0' >
&lt ; 表格 >
< >
< row number =' 0' >
< col 数字 =' 1' header =' true' > < / col >
< col number =' 2' header =' true' > B < / col >
< / row pan> >
< row 数字 =' 1' >
< col number =' 1' 标题 =' false' > ValueA1 < / col >
< col number =' 2' header =' false' > ValueB1 < / col >
&lt ; / row >
< row number =' 2' >
< col number =' 1 ' header =' false' > ValueA2 < / col
>
< col number =' 2' 标题 =' false' > ValueB2 < / col >
< / row >
< / rows >
< / table > ;

//从字符串
创建xml文档XDocument xdoc = XDocument.Parse(xcontent);

//获取元素的名称,其级别和否。子节点
var result = xdoc.Descendants()
.Select(x => new
{
NodeName = x.Name,
NodeLevel = x.AncestorsAndSelf ()。Count(),
ChildsCount = x.Descendants()。Count()
}

.Distinct();





结果:



  NodeName NodeLevel ChildsCount  
表1 10
行2 9
行3 2
col 4 0





您可能对 XmlElement的其他属性和方法感兴趣类 [ ^ ]。最有趣的是 XElement.AncestorsAndSelf Method() [ ^ ]


how to get total number of child nodes of xml file and total elements in each child node.[i want to display the xml file in table layout control at run time for that i need to count rows and coloms]
how to get count of rows and colums at runtime based on xml file.

Parse the file with one of the XML classes available in .NET, such as https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx[^].


Have a look at example:
//define xml document content
string xcontent = @"<?xml version='1.0' ?>
        <table>
        <rows>
        <row number='0'>
            <col number='1' header='true'>A</col>
            <col number='2' header='true'>B</col>
        </row>
        <row number='1'>
            <col number='1' header='false'>ValueA1</col>
            <col number='2' header='false'>ValueB1</col>
        </row>
        <row number='2'>
            <col number='1' header='false'>ValueA2</col>
            <col number='2' header='false'>ValueB2</col>
        </row>
        </rows>
        </table>";

//create xml document from string
XDocument xdoc = XDocument.Parse(xcontent);

//get the name of element, its level and no. of subnodes
var result = xdoc.Descendants()
        .Select(x=>new
            {
                NodeName = x.Name,
                NodeLevel = x.AncestorsAndSelf().Count(),
                ChildsCount = x.Descendants().Count()
            }
        )
        .Distinct();



Result:

NodeName NodeLevel ChildsCount
table    1         10
rows     2         9
row      3         2
col      4         0



You might be interested in other properties and methods of XmlElement class[^]. A most interesting is XElement.AncestorsAndSelf Method ()[^]