LINQ to XML getting XElement values

前端 未结 1 803
北海茫月
北海茫月 2021-01-29 04:16

I am having an issue with getting some values back from LINQ to XML query. I have got the XML from a SOAP web service and passed this through and parsed this into an XDocument

1条回答
  •  -上瘾入骨i
    2021-01-29 05:13

    This is what's causing you the headache:

    xmlns="http://webservices.whitespacews.com/"
    

    That's setting the default namespace for the element and its descendants - so you need to look for elements with a local name of Collections and that namespace. Ditto the other elements. Fortunately, LINQ to XML makes that easy for you:

    XNamespace ns = "http://webservices.whitespacews.com/";
    ...
    var test = xmlDoc.Descendants(ns + "Collection")
                     .Select(x => new
                     {
                         day = x.Element(ns + "Day").Value,
                         date = x.Element(ns + "Date").Value
                     });
    

    I suspect your test2 collection would have elements, but because it won't be able to find the Day and Date elements, so fetching the Value property will result in a NullReferenceException.

    Also note that there's no need for you to create your own reader etc. I would write your code as:

    XNamespace ns = "http://webservices.whitespacews.com/";
    XDocument doc;
    using (var stream = response.GetResponseStream())
    {
        doc = XDocument.Load(stream);
    }
    var query = xmlDoc.Descendants(ns + "Collection")
                      .Select(x => new
                      {
                          Day = x.Element(ns + "Day").Value,
                          Date = x.Element(ns + "Date").Value
                      });
    

    0 讨论(0)
提交回复
热议问题