C#Linq to XML检查元素是否存在 [英] C# Linq to XML check if element exists

查看:366
本文介绍了C#Linq to XML检查元素是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文档,如下所示:

I have an XML document as follows:

<Database>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
 </SMS>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
 </SMS>
</Database>

我正在尝试检查文档中是否存在父SMS节点的数字子节点(出于验证目的,以避免插入重复的数据).

I am trying to check whether the number child node of the parent SMS node exists in the document (for validation purposes to avoid inserting duplicate data).

对潜在解决方案有何建议?

Any advice on a potential solution?

该元素将与输入字符串进行比较.例如if(inputNumber == xmlDocNumber){//不要插入新元素}

The element will be compared to an input string. For example if(inputNumber == xmlDocNumber){ //Don't Insert New Element }

推荐答案

我会建议使用Count()的方式稍有不同-使用Any().优点是Any()一旦获得任何匹配项便可以立即停止:

I'll suggest a slightly different tack to using Count() - use Any(). The advantage is that Any() can stop as soon as it gets any matches at all:

var smsWithNoNumber = main.Descendants("SMS")
                          .Where(x => !x.Elements("Number").Any());

在这种情况下,赔率不会太大,但是在Count()可能不得不算一百万次点击只是告诉您至少有一次的情况下,这是一个有用的窍门.我想这也可以清楚地说明您的意思.

In this case it won't make much odds, but in cases where Count() might have to count a million hits just to tell you that there was at least one, it's a useful trick to know. I'd say it's also a clearer indicator of what you mean.

这篇关于C#Linq to XML检查元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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