Mandar Patil
Mandar Patil

Reputation: 538

How to select XML node with different XML namespace?

I have a XML document which looks like :

<stReq xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <EvalRes>
    <RenDtSrc xmlns="http://fakeurl.com/somthing/facade/params">
          <ContentType>application/pdf</ContentType>
          <DocumentName>Name</DocumentName>
          <Content>Doc Content</Content>
    </RenDtSrc>
  </EvalRes>
</stReq>

From a asp.net application, I am trying to check if a node <RenDtSrc> exists in a document or not. Following is the code I am using to read XML file and node element

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("D:\\Test\\Doc1.xml");
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/stReq/EvalRes/RenDtSrc");

Count of nodeList returns zero even though there are child nodes inside it. I think its something to do with namespace manager but I can't figure it out. Any help would be appreciated.

Upvotes: 0

Views: 50

Answers (2)

Clive Seebregts
Clive Seebregts

Reputation: 2034

XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("//stReq/EvalRes/node()/*");

Output:

Node [0] = {Element, Name="ContentType"}
Node [1] = {Element, Name="DocumentName"}
Node [2] = {Element, Name="Content"}

Upvotes: 0

bhanu.cs
bhanu.cs

Reputation: 1365

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("D:\\Test\\Doc1.xml");
var nsm = new XmlNamespaceManager(xmlDoc.NameTable);
nsm.AddNamespace("s", "http://fakeurl.com/somthing/facade/params");
XmlNodeList nodeList = xmlDoc.SelectNodes("//s:RenDtSrc", nsm);

Upvotes: 1

Related Questions