Rober
Rober

Reputation: 73

XML namespace issue C#

I have an XML and i am trying to get the node from XmlDocument, but due to some namespace issues, it is not returning me back the node I want.

The following is my XML.

<?xml version="1.0" encoding="iso-8859-1"?>
<message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.origoservices.com">
  <content>
    <application>
      <personal_client id="pc1">
        <title>Mr</title>
        <forenames>Test</forenames>
        <surname>SurName</surname>
        <sex>Male</sex>
      </personal_client>
      <personal_client id="pc2">
        <title>Mr</title>
        <forenames>Test</forenames>
        <surname>SurName</surname>
        <sex>Male</sex>
      </personal_client>
      <personal_client id="pc3">
        <title>Mr</title>
        <forenames>Test</forenames>
        <surname>SurName</surname>
        <sex>Male</sex>
      </personal_client>
    </application>
  </content>
</message>

Following is the C# code which I am using to get all the personal_client nodes from the above xml.

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.PreserveWhitespace = true;
XMLDoc.Load("XML Loaded successfully");

XmlNamespaceManager nsmgr = new XmlNamespaceManager(XMLDoc.NameTable);
nsmgr.AddNamespace("origo", "http://www.origoservices.com");
nsmgr.PushScope();

XmlNodeList xnList = XMLDoc.SelectNodes("//origo:message/m_content/application/personal_client", nsmgr);

All the time it is returning 0 nodes, please help.

Upvotes: 0

Views: 504

Answers (2)

Innat3
Innat3

Reputation: 3576

Here's another way

//Using the file path
var clients = XDocument.Load(xmlFilePath)
               .Descendants(XName.Get("personal_client", "http://www.origoservices.com"));

//Using the file content
var clients = XDocument.Parse(xmlFileContent)
               .Descendants(XName.Get("personal_client", "http://www.origoservices.com"));

And this way you can avoid putting the namespace

.Descendants().Where(x => x.Name.LocalName == "personal_client");

Upvotes: 1

Markus
Markus

Reputation: 22436

You need to specify the namespace for each element of the query because the default namespace is also applied to the sub-nodes. I've put your sample XML in a file called XmlFile1.xml and created the following sample:

var XMLDoc = new XmlDocument();
XMLDoc.Load("XmlFile1.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(XMLDoc.NameTable);
nsmgr.AddNamespace("origo", "http://www.origoservices.com");
XmlNodeList xnList = XMLDoc.SelectNodes("//origo:message/origo:content/origo:application/origo:personal_client", nsmgr);

This code retrieves 3 nodes.

Upvotes: 1

Related Questions