如何在c#的xml中计算每个节点中的子节点和元素的数量 [英] how to get count of child nodes and elements in each node in c# of xml
问题描述
如何获取xml文件的子节点总数和每个子节点中的总元素。[我想在运行时在表格布局控件中显示xml文件,我需要计算行和列]
如何在运行时基于xml文件获取行和列的计数。
使用.NET中提供的XML类之一解析文件,例如 https://msdn.microsoft.com/ en-us / library / system.xml.xmldocument(v = vs.110).aspx [ ^ ]。
看看例子:
//定义xml文档内容
string xcontent = @<? xml version =' 1.0' ? >
< ; 表格 >
< 行 >
< row number =' 0' >
< col 数字 ='1' header =' true' > < / col >
< col number =' 2' header =' true' > B < / col >
< / row >
< row 数字 =' 1' >
< col number =' 1' 标题 =' false' > ValueA1 < / col >
< col number =' 2' header =' false' > ValueB1 < / col >
< ; / row >
< row number =' 2' >
< col number =' 1 ' header =' false' > ValueA2 < < span class =code-leadattribute> / col >
< col number =' 2' 标题 =' false' > ValueB2 < / col >
< / row >
< / rows < span class =code-keyword>>
< / 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() [< a href =https://msdn.microsoft.com/en-us/library/bb346865%28v=vs.110%29.aspxtarget =_ blanktitle =New Window> ^ ]
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 ()[^]
这篇关于如何在c#的xml中计算每个节点中的子节点和元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!