How can I retrieve specific nodes when having a namespace in the xml element?

If you have the following xml file which contains a xmlns parameter, then you can't use simple SelectSingleNode to retrieve a specific node.

Used Classes:

XmlDocument
XmlNode
XmlNamespaceManager

XML File:

<?xml version="1.0" encoding="utf-8" ?>
<OfferSheetXML xmlns="
http://localhost/OfferSheetSchema.xsd" >
  <Offer>
    <OfferSheetId>31</OfferSheetId>
  </Offer>
</OfferSheetXML>


Now try to run the following code with the above xml:

<%@ Import Namespace="System.Xml"%>
<%@ Page Language="C#" Debug="true"%>

<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Server.MapPath("temp.xml"));

    XmlNode node = xmlDoc.SelectSingleNode("//OfferSheetXML");
    Response.Write ("Node Name : " + node.Name);
}
</script>


Running the above code will generate the following error message:

System.NullReferenceException: Object reference not set to an instance of an object.
Line 16:  Response.Write ("Node Name : " + node.Name);


The solution is that you will also have to specifiy the namespace for the xpath. The following code solves the problem and retrives the node:

<%@ Import Namespace="System.Xml"%>
<%@ Page Language="C#" Debug="true"%>

<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Server.MapPath("temp.xml"));

    XmlNamespaceManager nsmRequest = new XmlNamespaceManager(xmlDoc.NameTable);
    nsmRequest.AddNamespace("ns1", "
http://localhost/OfferSheetSchema.xsd");
    XmlNode node = xmlDoc.SelectSingleNode("//ns1:OfferSheetXML", nsmRequest);

    Response.Write ("Node Name : " + node.Name);
}
</script>


Thanks to Kevin Yu for his help.

Filed under:

Comments

# Sonu Kapoor said:

Please see also:
http://asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=639424

Monday, July 19, 2004 12:02 PM

Leave a Comment

(required) 
(required) 
(optional)
(required)