dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » XML
Language: XML
Expertise: Beginner
Jun 14, 2004

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Retrieve Specific Nodes When They Contain an xmlns Namespace Parameter

When an XML file contains a xmlns parameter, you can't use simple SelectSingleNode to retrieve a specific node. Take the following code, for example:

<?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 to specifiy the namespace for the XPath. The following code solves the problem and retrieves 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>
Sonu Kapoor
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date