advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 5/5 | Rate this item | 4 users have rated this item.
Expertise: Beginner
Language: XML
June 14, 2004
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
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs