Linq To Xml problems using XElement's method Elements(XName)

前端 未结 2 1113
故里飘歌
故里飘歌 2021-01-13 22:00

I have a problem using Linq To Xml.

A simple code. I have this XML:




        
2条回答
  •  既然无缘
    2021-01-13 22:26

    Pretty easy: there's a XML namespace in play, which you're ignoring:

    You need to add that to your Linq-to-XML queries!

    Something like:

    XNamespace ns = "http://www.example.com";
    

    and then

    XRoot.Elements(ns + "contact") 
    

    and of course, also use the XML namespace when accessing the child elements:

    var results = from e in XRoot.Elements("contact") 
                  select new Contact(e.Element(ns + "name").Value, 
                                     e.Element(ns + "email").Value, 
                                     "1-1-1", null, null);
    

    That should help. See the MSDN docs on Working with XML Namespaces for more details.

提交回复
热议问题