C# check an element exists while using LINQ to XML

前端 未结 6 986
慢半拍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:35

    Have you tried checking if the SuperType element exists before trying to read the value from it?

    ...
    where (c.Element("SuperType") != null && c.Element("SuperType").Value == "1")
    ...
    
    0 讨论(0)
  • 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";
    
    0 讨论(0)
  • 2021-01-02 08:37

    Try this:

    var superType = (from c in from c in linquee.Descendants("customer")
                     where (string) c.Element("SuperType") == "1"
                     select c).ToList();
    

    Basically if you cast a null XElement reference to string, you'll get a null reference (which you can compare with "1").

    An alternative would be to cast to int? which (IIRC) will return a null int? value if the element is missing, but go bang if it's present but non-numeric:

    var superType = (from c in from c in linquee.Descendants("customer")
                     where (int?) c.Element("SuperType") == 1
                     select c).ToList();
    
    0 讨论(0)
  • 2021-01-02 08:38

    You should be able to just add a check for null

    where c.Element("SuperType") != null 
    && [your other criteria]
    
    0 讨论(0)
  • 2021-01-02 08:52

    I would do it like this:

    var superType = linquee.Descendants("customer").
        Where(c => c.Element("SuperType") != null 
            && c.Element("SuperType").Value == "1");
    
    0 讨论(0)
  • 2021-01-02 09:00

    Should also be able to clean this kinda stuff up with extensions, something like..

    public string Element_valStr(XElement xElm, string xName)
    {
        if (xElm.Element(xName) == null) return string.empty;
        return xElm.Element(xName).Value;
    }
    

    and then just:

    var superType = (from c in linquee.Descendants("customer")  
                      where (c.Element_valStr("SuperType") == "1")
                      select c).ToList();
    
    0 讨论(0)
提交回复
热议问题