Access Child nodes with namespace using xpath Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Access Child nodes with namespace using xpath without wasting too much if your time.

The question is published on by Tutorial Guruji team.

How can I read the content of the childnotes using Xpath?

I have already tried this:

var xml = new XmlDocument();
            
xml.Load("server-status.xml");
var ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ns", "namespace");
var node = xml.SelectSingleNode("descendant::ns:server[ns:ip-address]", ns)
Console.WriteLine(node.InnerXml)

But I only get a string like this:

<ip-address>127.0.0.50</ip-address><name>Server 1</name><group>DATA</group>

How can I get the values individually?

Xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<server-status xmlns="namespace">
    <server>
        <ip-address>127.0.0.50</ip-address>
        <name>Server 1</name>
        <group>DATA</group>
    </server>
</server-status>

Answer

You’re using XML namespaces in XPath correctly.

However, your original XPath,

descendant::ns:server[ns:ip-address]

says to select all ns:server elements with ns:ip-address children.

If you wish to select the ns:ip-address children themselves, instead use

descendant::ns:server/ns:ip-address

Similarly, you could select ns:name or ns:group elements.

We are here to answer your question about Access Child nodes with namespace using xpath - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji