XDocument Reading XML file with Root element having namespaces

后端 未结 4 1014
故里飘歌
故里飘歌 2021-01-07 06:13

I am having some trouble parsing an XML file with the root node having multiple namespaces. I want to get a list of nodes \'object\' with type string containing \'UserContro

相关标签:
4条回答
  • 2021-01-07 06:22

    When you call Decendants with a XName parameter the XName'sNameSpace (which happened to be empty) is actually incorporated into the Name in addition to LocalName. So you can query just byLocalName

    p.Descendants().Where(p=>p.Name.LocalName == "object")
    
    0 讨论(0)
  • 2021-01-07 06:31

    Try using the namespace:

    var ns = new XNamespace("http://www.springframework.net");
    IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");
    
    0 讨论(0)
  • 2021-01-07 06:39

    If you are using decedent than you have to add name space like below

     XDocument webXMLResource = XDocument.Load(@"../../../../Web.xml");
     XNamespace _XNamesapce = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
     IEnumerable<XElement> values = from ele in webXMLResource .Descendants(_XNamesapce + "object")
                                    select ele;
    

    Hope it will work for you

    0 讨论(0)
  • 2021-01-07 06:49

    One more trick with namespaces - you can use XElement.GetDefaultNamespace() to get default namespace of root element. Then use this default namespace for querying:

    var xdoc = XDocument.Load(path_to_xml);
    var ns = xdoc.Root.GetDefaultNamespace();
    var objects = xdoc.Descendants(ns + "object");
    
    0 讨论(0)
提交回复
热议问题