0

I am not able to parse XML document with a default namespace.

If I remove the namespace xmlns="http://java.sun.com/xml/ns/j2ee from the XML file, then I am able to get values in nodelist. I don't want to use Linq.

XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    <display-name>Test - My tomcat webapp</display-name>
</web-app>

C# code:

String strFileUsers = @"E:\\Dot_net\\XML_Parser\\demo\\web_org.xml";
XmlDocument docUsers = new XmlDocument();

try
{
    docUsers.Load(strFileUsers);
}
catch (Exception)
{
    MessageBox.Show("Cannot open file ");
    return;
}

try
{
    XmlNodeList nodeList = docUsers.SelectNodes("//display-name");

    Console.WriteLine(nodeList.Count);
}   
catch (Exception ex)
{
    return;
}

1 Answer 1

3

You should use an XmlNamespaceManager in your call

XmlNamespaceManager ns = new XmlNamespaceManager(docUsers.NameTable);
ns.AddNamespace("test", "http://java.sun.com/xml/ns/j2ee");  
XmlNodeList nodeList = docUsers.SelectNodes("//test:display-name",ns);
Sign up to request clarification or add additional context in comments.

6 Comments

Still getting count null.
In my case xmlns append after xml tag like <display-name xmlns...>
Could you please publish sample XML
Already added in question but I have see this type of behavior in debugging.
The code works well with sample you published.That is the reason why I asked for another sample as you mentioned ..<display-name xmlns...>...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.