Click here to Skip to main content
15,846,009 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ,
I am trying to select an xml node without parent node , but am not getting the value . Someone please help .

What I have tried:

XmlNodeList nodes = root.SelectNodes("//sdnDetails");
        foreach (XmlNode node in nodes)
            XmlNode fnamexml = node.SelectSingleNode("firstName");
            if(fnamexml != null)
                string a = fnamexml.InnerText;

xml :
<?xml version="1.0" standalone="yes"?><sdnList xmlns:xsi="" xmlns="">
<firstName>Ismail Abdul Salah</firstName>
Updated 24-Feb-23 3:22am
Member 15627495 24-Feb-23 3:30am    
as XML tree is a 'hard' hierarchy, you have to mention litterals about 'depth',
when you write "//" you are at 'root' level
try :  root.selectNodes("//sdnDetails/sdnType");

but take the time to read about '' 'LINQ' for Xml'' too, because of lot of feature to fetch Xml tree by LINQ query.

1 solution

Your XML document has a default namespace of "".

Unfortunately, the System.Xml classes don't support default namespaces. Instead, you'll need to use an XmlNamespaceManager to define an alias for the default namespace, and use that in your queries:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(root.OwnerDocument.NameTable);
nsmgr.AddNamespace("d", root.NamespaceURI);

XmlNodeList nodes = root.SelectNodes("//d:sdnDetails", nsmgr);
foreach (XmlNode node in nodes)
    XmlNode fnamexml = node.SelectSingleNode("d:firstName", nsmgr);

It's slightly easier with LINQ to XML[^]:
XNamespace ns = root.Name.Namespace;
IEnumerable<XElement> nodes = root.Descendants(ns + "sdnDetails");
foreach (XElement node in nodes)
    XElement fnamexml = node.Element(ns + "firstName");
Share this answer
Member 12926744 24-Feb-23 5:40am    
Thank you, its working
PIEBALDconsult 24-Feb-23 8:25am    
Ugh, default namespaces, the worst idea ever.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900