C# Linq to XML check if element exists

前端 未结 3 1216
傲寒
傲寒 2020-12-06 04:25

I have an XML document as follows:


 
   \"+447528349828\" 
   \"09/06/24 
          


        
相关标签:
3条回答
  • 2020-12-06 05:05

    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

    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>
    
    0 讨论(0)
  • 2020-12-06 05:06

    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());
    

    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.

    0 讨论(0)
  • 2020-12-06 05:11

    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:

    string pattern = String.Format("/Database/SMS/Number[. = '{0}']", number);
    if (myDoc.SelectSingleNode(pattern) != null)
    {
       // number already exists in document
    }
    
    0 讨论(0)
提交回复
热议问题