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

前端 未结 2 1094
故里飘歌
故里飘歌 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:

    <data xmlns="http://www.example.com"  
          **************************
    

    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.

    0 讨论(0)
  • 2021-01-13 22:48

    For me I solved it like that because I didn't had a namespace in my XML:

    xmldoc.Root.Elements("contact");
    

    I forgot to use the "Root" method.

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