简体   繁体   English

C#Linq XML查找指定的元素

[英]C# Linq XML Find Specified element

Please could someone post an example of how to check if an element exists in an xml file using linq? 请有人可以发布一个示例,说明如何使用linq检查xml文件中是否存在元素?

Here is the xml document: 这是xml文档:

<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>

I want to be able to specify a number and check if it exists 我希望能够指定一个数字并检查它是否存在

How about: 怎么样:

public static bool HasNumber(XDocument doc, string number)
{
    return doc.Descendants("Number")
              .Any(element => element.Value == number);
}

(One point to note - it looks a bit odd that you've got quotes round the numbers in the XML file. Do you have to have them?) (需要注意的一点-您在XML文件中的数字周围加上了引号,这似乎有些奇怪。您是否必须使用引号?)

I think this should do it. 我认为应该这样做。

var exists = xml.Descendants("Number")
                .Any(e => String.Equals(
                   (string)e, 
                   number, 
                   StringComparison.OrdinalIgnoreCase))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM