如何使用C#计算特定条件的Xml元素 [英] How to count Xml elements for particular condition using C#

查看:63
本文介绍了如何使用C#计算特定条件的Xml元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <  型号 >  
< 对象 type = Book >
< 组件 id = 123 >
< 元素 id = 123 >
< 文章 id = 1 >
< / Article > ;
< 文章 id = 2 >
< / Article >
< /元素 >
< /有限公司mponent >
< / object >
< / Model >





在如果至少有一个Article元素可用,则在XMl文件上面

然后应该计算对象。



类似如何计算文件是否有大线。

但结构应该是上面的。



如何做到这一点

解决方案

最好的办法是使用linQ,比如



  var  count = XDocument 
.Load( test.xml
.XPathSelectElements( // Elemen t
.Count();





并寻找特定的孩子,见下文。 />




 IEnumerable< XElement> elements = 
来自 el in root.Elements( 元素
其中字符串el.Element( 文章)<>
选择 el ;


<Model>
<Object type="Book">
<Component id="123">
<Element id="123">
<Article id="1">
</Article>
<Article id="2">
</Article>
</Element>
</Component>
</Object>
</Model>



In the above XMl file if at least one Article element is available
then the Object Should be counted.

Similarly how to count if the file has large lines.
But the structure should be the above on.

How to do this

解决方案

Best way would be using linQ, something like

var count = XDocument
    .Load("test.xml")
    .XPathSelectElements("//Element")
    .Count();



and to look for particular child see below.


IEnumerable<XElement> elements =
    from el in root.Elements("Element")
    where (string)el.Element("Article") <> ""
    select el;


这篇关于如何使用C#计算特定条件的Xml元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆