简体   繁体   中英

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.

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);
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("//stReq/EvalRes/node()/*");

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM