C# check an element exists while using LINQ to XML

前端 未结 6 1029
慢半拍i
慢半拍i 2021-01-02 08:32

OK, bit of a random question, but the best way to do this is to just add the code, you\'ll be able to see what I mean straight away:

XML:



        
6条回答
  •  忘掉有多难
    2021-01-02 08:36

    I found a nice solution using Any() in combination with a conditional operator:

    result = entry.Elements(ArbitraryElement).Any() ? (entry.Element(ArbitraryElement).Attributes(ArbitraryAttribute).Any() ? entry.Element(ArbitraryElement).Attribute(ArbitraryAttribute).Value : "-1") : "-1"

    The trick is to use Elements() together with Any() to check if the element exists (same for Attributes())

    So for this example it would be something like this:

    var superType = from c in linquee.Descendants("customer")  
                    select c.Elements("SuperType").Any() ? c.Element("SuperType").Value : "0";
    

提交回复
热议问题