Fetching Values from XML using XQuery


I'm not able to fetch value from the following XML files:

Can anyone tell me to fetch - lets "Deposit Policy" information from this xml files - using XQuery - or let me know if any better method is available

<?xml version="1.0" ?>
<HotelML xmlns="www.test.com">
 <Route Destination="01" Source="00">
  <Operation Action="Create" App="TIDispatcher" AppVer="" DataPath="/HotelML" StartTime="2008-11-08T14:26:28.694+00:00" Success="true" TotalProcessTime="251" />
 <Property xml:lang="en" Code="BW;05250" Name="Best Western Gateway Inn" Token="1226154388618">
  <Amenity xml:lang="en" Code="BAR" Description="Bar/Lounge" />
  <Amenity xml:lang="en" Code="REST" Description="Restaurant" />
  <Amenity xml:lang="en" Code="POOL" Description="Pool" Property="true" />
  <Amenity xml:lang="en" Code="ROOM" Description="Room Service" Property="true" />
  <AreaAttraction Name="Restaurants:" />
  <AreaAttraction Name="Nearby Cities:" />
 <AreaAttraction Description="* In the heart of Silicon Valley * 2 miles from the Great America Theme Park * 5 miles from the Winchester Mystery House * 6 miles from Santa Clara/San Jose Convention Center * 30 miles from Oakland Coliseum * 40 miles from Monterey Peninsula * 80 miles from Napa Wine Country" Name="Local attractions, events and activities include">
  <Media Link="05250_m.gif" MIME="image/gif" Type="Map" />
  <AreaAttraction Description="* 40 miles from San Francisco" Name="Nearby Cities" />
  <AreaAttraction Name="Local Attractions:" />
  <AreaAttraction Name="Transportation:" />
 <AreaAttraction Name="Area Map">
  <Media Link="05250_m.gif" MIME="image/gif" Type="Map" />
 <AreaAttraction Name="Area Map">
  <Media Link="05250_m.gif" MIME="image/gif" Type="Map" />
 <Brand Code="BW">
  <Email Address="nguyenn@bestwestern.com" />
  <CancelPolicy Description="Cancellation policies vary from hotel to hotel. Most current and accurate cancellation policies will appear on your confirmed reservation notification." />
  <DepositPolicy AcceptedCreditCard="AX, CB, DC, DS, CA, VI, AM, JC" />
  <GeneralInfo AirportText="San Jose International Airport" AreasServed="San Jose, Santa Clara, Sunnyvale, Palo Alto, Milpitas, California" CheckInTime="3:00 P.M." CheckOutTime="12:00 Noon" HotelRating="AAA Rating: 3 Diamonds; MOBIL Rating: 2 Stars" LocationDescription="From Highway 101, take the Trimble Road Exit, and then take the first right on Seaboard Avenue and follow the signs to the Best Western Gateway Inn." NativeCurrency="USD" NumberOfFloors="2" NumberOfRooms="146" OpenEffectiveDate="1996-12-15" PropertyDescription="Gracious hospitality sets the pace at the Best Western Gateway Inn. Whether you are traveling for business or pleasure, our close attention to detail will make your stay in San Jose a memorable one. At the Best Western Gateway Inn you will find comfort and pleasure that are reminiscent of times past. Upon entering our lobby, you will be greeted by an enthusiatic helpful staff - 24 hours a day." RateDisclaimer="Indicative rates are for search purposes only. The entire range of rates may not be available during certain seasons or other specified periods of time. Check for specific rate availability when making a reservation." YearRenovatedText="1992" />
  <GeoInfo Accuracy="Property" Latitude="37.378991" Longitude="-121.938126" TimeZone="Pacific Standard Time" />
  <GuaranteePolicy Description="You must use a credit card to book online." />
  <Media Link="05250_b1a.jpg" MIME="image/jpeg" Type="Picture" />
  <Media Link="05250_b8a.jpg" MIME="image/jpeg" Type="Picture" />
  <Media Link="05250_b9a.jpg" MIME="image/jpeg" Type="Picture" />
  <Phone Number="(408)435-8800" />
  <Phone Number="1-800-437-8855" Type="Reservation" />
  <Phone Number="408-435-8879" Type="FAX" />
  <PostalAddress City="San Jose" CountryCode="US" Line1="2585 Seaboard Avenue" PostalCode="95131" StateCode="CA" />

Who is Participating?
Geert BormansConnect With a Mentor Information ArchitectCommented:
This should get you started
  	// create XML document object
  	XmlDocument xmlDocument = new XmlDocument();
  	// I assume that you want to load from a webservice instead   
  	// create the namespace manager here
    XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);   
    namespaceManager.AddNamespace("ns", "www.test.com");   
  	// select the node, I am not sure about the value part
  	policy = xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard").value;

Open in new window

Geert BormansInformation ArchitectCommented:
If all you need is the deposit policy,
you can do that in a single XPath "//xxx:DepositPolicy" if you first bind xxx to  "www.test.com", so you also need a namespace manager
whatever  language you are using to deal with this, should allow you to do that

How would you perform the XQuery? Is this in a database?

Tell me first how you were going to tackle all around the XQuery (programming language, tool or applications)
then I can give you the best fit.
XQuery seems somewhat ocverkill for this problem
RadheRadheAuthor Commented:
This is a response which I get from a third party website which is integrated with our site.

I have got "Web Services in C#" with integrate with this third party application

In terms on programming language - I need to find a way in C#...

Any better and faster of fetching values from this XML - as u said above XQuery might overkill it....

Thanks alot for quick reply
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

RadheRadheAuthor Commented:

Thanks alot for example. You would advise not to use XQuery for this..

Also just one small request: Let's say I want to fetch all MEDIA stuff from it - then how it write some sort of loop which fetches all the data for me.

I'm very new to .net so apologies for asking may be siimple questions.

RadheRadheAuthor Commented:
When I write this code in C#, I'm get following error - any advise:
XPathException: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.]
   MS.Internal.Xml.XPath.CompiledXpathExpr.get_QueryTree() +63
   System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr, XPathNodeIterator context) +37
   System.Xml.XPath.XPathNavigator.Evaluate(XPathExpression expr) +9
   System.Xml.XPath.XPathNavigator.Select(XPathExpression expr) +8
   System.Xml.XPath.XPathNavigator.Select(String xpath) +24
   System.Xml.XmlNode.SelectSingleNode(String xpath) +29
   _Default.Page_Load(Object sender, EventArgs e) +103
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43
   System.Web.UI.Control.OnLoad(EventArgs e) +80
   System.Web.UI.Control.LoadRecursive() +49
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3750


Geert BormansInformation ArchitectCommented:
If you need very complex queries you could start thinking about XQuery.
If you need to reconstruct a different XML, using complex queries, you could think of XQuery or even XSLT

If you simply need a list of all the media elements, you can build an iterator
policy = xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard").value;
would then become
list = xmlDocument.SelectNodes("//ns:Media");
Then you have a list of nodes, and you can work on them, maybe get the @link from them

I forgot to pass the namespacemanager in the XPath, sorry
policy = xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard").value;
should be
policy = xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard", namespaceManager).value;

Note that I don't have much C# experience myself, so we might run in a block at some point, but so far it is OK
RadheRadheAuthor Commented:

I just tried this:

  // create XML document object
        XmlDocument xmlDocument = new XmlDocument();
        // I assume that you want to load from a webservice instead  

        // create the namespace manager here
        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
        namespaceManager.AddNamespace("ns", "http://www.xpegs.com/v2001Q3/HotelML");

        Response.Write(xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard", namespaceManager));

And Result I'm getting is : System.Xml.XmlAttribute

Any advise... - Means I'm not able to fetch the "AcceptedCreditCard" details.

Geert BormansInformation ArchitectCommented:
that means you are writing the type of the node to the response,
that is good, you are actually fetching an attribute
Response.Write(xmlDocument.SelectSingleNode("//ns:DepositPolicy/@AcceptedCreditCard", namespaceManager).value);
RadheRadheAuthor Commented:
Then how to get the value of that attribute.....
RadheRadheAuthor Commented:
Excellent Resolved.

Any thing else you want to add - which i should i keep in mind while fetching the value....

As I mean new to XML - the XML which im receiving is the one mentioned above.

I need to fetch value and send this back to our application server.

So any advise - would be highly appreciated...
RadheRadheAuthor Commented:
Can you please advise how to iterate through this XML file: and fetch all values related to MEDIA
Geert BormansInformation ArchitectCommented:
Here is how you could handle nodelists with an iterator
(this one lists the attribute values for the @Link)

        XmlNodeList nodes = xmlDocument.SelectNodes("//ns:Media/@Link", namespaceManager);
        foreach (XmlNode node in nodes)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.