简体   繁体   English

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

[英]C# Linq to XML check if element exists

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){//不插入新元素}

I'll suggest a slightly different tack to using Count() - use Any() . 我建议使用Count()稍微不同一点 - 使用Any() The advantage is that Any() can stop as soon as it gets any matches at all: 优点是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. 在这种情况下它不会有太大的可能性,但是在Count()可能需要计算一百万次点击只是为了告诉你至少有一次,这是一个有用的技巧。 I'd say it's also a clearer indicator of what you mean. 我会说这也是你所说的更明确的指标。

Assuming that you have your number in some canonicalized form and your XML is loaded into an XmlDocument or 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
}

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 您可以通过循环SMS节点来应用转换数据的XSL文档,并排除任何具有重复的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>

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

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