XDocument Reading XML file with Root element having namespaces
14,690
Solution 1
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");
Solution 2
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")
Solution 3
Try using the namespace:
var ns = new XNamespace("http://www.springframework.net");
IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");
Author by
user2788385
Updated on June 04, 2022Comments
-
user2788385 almost 2 years
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 'UserControlLibrary' :
XML File:<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd"> <!-- master pages --> <object type="RLN.Site, RLN"> <property name="ContainerBLL" ref="ContainerBLL"></property> <property name="UserBLL" ref="UserBLL"></property> <property name="TestsBLL" ref="TestsBLL"></property> <property name="GuidBLL" ref="GuidBLL"></property> </object> <object type="RLN.UserControlLibrary.topleveladmin, RLN.UserControlLibrary"> <property name="ContainerBLL" ref="ContainerBLL"></property> <property name="UserBLL" ref="UserBLL"></property> <property name="GuidBLL" ref="GuidBLL"></property> </object> <object type="RLN.UserControlLibrary.topleveladminfloat, RLN.UserControlLibrary"> <property name="ContainerBLL" ref="ContainerBLL"></property> <property name="UserBLL" ref="UserBLL"></property> </object> </objects>
I have tried:
XDocument webXMLResource = XDocument.Load(@"../../../../Web.xml"); IEnumerable<XElement> values = webXMLResource.Descendants("object");
with no results being returned.