Click here to Skip to main content
15,885,546 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:

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



xml :
XML
<?xml version="1.0" standalone="yes"?><sdnList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/sdnList.xsd">
<publshInformation>
<Publish_Date>12/15/2022</Publish_Date>
<Record_Count>447</Record_Count></publshInformation>
<sdnDetails>
<uid>9639</uid>
<firstName>Ismail Abdul Salah</firstName>
<lastName>HANIYA</lastName>
<sdnType>Individual</sdnType>
</sdnDetails>
</sdnList>
Posted
Updated 24-Feb-23 2:22am
v2
Comments
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 "http://tempuri.org/sdnList.xsd".

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:
C#
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[^]:
C#
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
 
Comments
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)



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