C# Linq to XML 检查元素是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1039628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:44:33  来源:igfitidea点击:

C# Linq to XML check if element exists

c#xmllinqlinq-to-xml

提问by Goober

I have an XML document as follows:

我有一个 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 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).

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

Any advice on a potential solution?

关于潜在解决方案的任何建议?

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

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

采纳答案by Jon Skeet

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:

我会建议一个稍微不同的策略来使用Count()-使用Any()。优点是 Any() 可以在获得任何匹配项时立即停止:

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

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.

在这种情况下,它不会有太大的可能性,但在Count()可能不得不计算一百万次点击只是为了告诉您至少有一次点击的情况下,这是一个有用的技巧。我想说这也是你的意思的更清晰的指标。

回答by Jay

You could apply an XSL document that translates the data by looping through the SMS nodes and excluding any that has a duplicate Number/text() value

您可以应用 XSL 文档,通过循环遍历 SMS 节点并排除任何具有重复 Number/text() 值的数据来转换数据

Check would be something like:

检查将是这样的:

<xsl:template match="SMS">
<xsl:variable name="parentNode" select="." />
<xsl:if test="preceding-sibling::SMS/Number/text()=$parentNode/Number/text()">
.....include a copy of node......
</xsl:if>
  </xsl:template>

回答by Robert Rossney

Assuming that you have your number in some canonicalized form and your XML is loaded into an XmlDocumentor some such, the simplest non-LINQ way to do it is with an XPath query:

假设您有某种规范化形式的号码,并且您的 XML 被加载到一个XmlDocument或一些这样的形式中,最简单的非 LINQ 方法是使用 XPath 查询:

string pattern = String.Format("/Database/SMS/Number[. = '{0}']", number);
if (myDoc.SelectSingleNode(pattern) != null)
{
   // number already exists in document
}