LINQ to XML optional element query

前端 未结 3 1904
心在旅途
心在旅途 2020-12-15 22:46

I\'m working with an existing XML document which has a structure (in part) like so:


    
         Bob 
           


        
相关标签:
3条回答
  • 2020-12-15 23:04

    In a similar situation I used an extension method:

        public static string OptionalElement(this XElement actionElement, string elementName)
        {
            var element = actionElement.Element(elementName);
            return (element != null) ? element.Value : null;
        }
    

    usage:

        id = g.OptionalElement("ID") ?? "none"
    
    0 讨论(0)
  • 2020-12-15 23:10

    How about:

    var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
                let idEl = g.Element("ID")
                select new
                {
                    name = (string)g.element("Name").Value,
                    id = idEl == null ? "none" : idEl.Value;
                };
    

    if this barfs, then FirstOrDefault() etc might be useful, else just use an extension method (as already suggested).

    0 讨论(0)
  • 2020-12-15 23:17

    XElement actually has interesting explicit conversion operators that do the right thing in this case.

    So, you rarely actually need to access the .Value property.

    This is all you need for your projection:

    var items =
        from g in xDocument.Root.Descendants("Group").Elements("Entry")
        select new
        {
            name = (string) g.Element("Name"),
            id = (string) g.Element("ID") ?? "none",
        };
    

    And if you'd prefer to use the value of ID as an integer in your anonymous type:

    var items =
        from g in xDocument.Root.Descendants("Group").Elements("Entry")
        select new
        {
            name = (string) g.Element("Name"),
            id = (int?) g.Element("ID"),
        };
    
    0 讨论(0)
提交回复
热议问题