Home > Articles > Web Services > XML

XML Reference Guide

📄 Contents

  1. XML Reference Guide
  2. Overview
  3. What Is XML?
  4. Informit Articles and Sample Chapters
  5. Books and e-Books
  6. Official Documentation
  7. Table of Contents
  8. The Document Object Model
  9. Informit Articles and Sample Chapters
  10. Books and e-Books
  11. Official Documentation
  12. DOM and Java
  13. Informit Articles and Sample Chapters
  14. Books and e-Books
  15. Implementations
  16. DOM and JavaScript
  17. Using a Repeater
  18. Repeaters and XML
  19. Repeater Resources
  20. DOM and .NET
  21. Informit Articles and Sample Chapters
  22. Books and e-Books
  23. Documentation and Downloads
  24. DOM and C++
  25. DOM and C++ Resources
  26. DOM and Perl
  27. DOM and Perl Resources
  28. DOM and PHP
  29. DOM and PHP Resources
  30. DOM Level 3
  31. DOM Level 3 Core
  32. DOM Level 3 Load and Save
  33. DOM Level 3 XPath
  34. DOM Level 3 Validation
  35. Informit Articles and Sample Chapters
  36. Books and e-Books
  37. Documentation and Implementations
  38. The Simple API for XML (SAX)
  39. Informit Articles and Sample Chapters
  40. Books and e-Books
  41. Official Documentation
  42. SAX and Java
  43. Informit Articles and Sample Chapters
  44. Books and e-Books
  45. SAX and .NET
  46. Informit Articles and Sample Chapters
  47. SAX and Perl
  48. SAX and Perl Resources
  49. SAX and PHP
  50. SAX and PHP Resources
  51. Validation
  52. Informit Articles and Sample Chapters
  53. Books and e-Books
  54. Official Documentation
  55. Document Type Definitions (DTDs)
  56. Informit Articles and Sample Chapters
  57. Books and e-Books
  58. Official Documentation
  59. XML Schemas
  60. Informit Articles and Sample Chapters
  61. Books and e-Books
  62. Official Documentation
  63. RELAX NG
  64. Informit Articles and Sample Chapters
  65. Books and e-Books
  66. Official Documentation
  67. Schematron
  68. Official Documentation and Implementations
  69. Validation in Applications
  70. Informit Articles and Sample Chapters
  71. Books and e-Books
  72. XSL Transformations (XSLT)
  73. Informit Articles and Sample Chapters
  74. Books and e-Books
  75. Official Documentation
  76. XSLT in Java
  77. Java in XSLT Resources
  78. XSLT and RSS in .NET
  79. XSLT and RSS in .NET Resources
  80. XSL-FO
  81. Informit Articles and Sample Chapters
  82. Books and e-Books
  83. Official Documentation
  84. XPath
  85. Informit Articles and Sample Chapters
  86. Books and e-Books
  87. Official Documentation
  88. XML Base
  89. Informit Articles and Sample Chapters
  90. Official Documentation
  91. XHTML
  92. Informit Articles and Sample Chapters
  93. Books and e-Books
  94. Official Documentation
  95. XHTML 2.0
  96. Documentation
  97. Cascading Style Sheets
  98. Informit Articles and Sample Chapters
  99. Books and e-Books
  100. Official Documentation
  101. XUL
  102. XUL References
  103. XML Events
  104. XML Events Resources
  105. XML Data Binding
  106. Informit Articles and Sample Chapters
  107. Books and e-Books
  108. Specifications
  109. Implementations
  110. XML and Databases
  111. Informit Articles and Sample Chapters
  112. Books and e-Books
  113. Online Resources
  114. Official Documentation
  115. SQL Server and FOR XML
  116. Informit Articles and Sample Chapters
  117. Books and e-Books
  118. Documentation and Implementations
  119. Service Oriented Architecture
  120. Web Services
  121. Informit Articles and Sample Chapters
  122. Books and e-Books
  123. Official Documentation
  124. Creating a Perl Web Service Client
  125. SOAP::Lite
  126. Amazon Web Services
  127. Creating the Movable Type Plug-in
  128. Perl, Amazon, and Movable Type Resources
  129. Apache Axis2
  130. REST
  131. REST Resources
  132. SOAP
  133. Informit Articles and Sample Chapters
  134. Books and e-Books
  135. Official Documentation
  136. SOAP and Java
  137. Informit Articles and Sample Chapters
  138. Books and e-Books
  139. Official Documentation
  140. WSDL
  141. Informit Articles and Sample Chapters
  142. Books and e-Books
  143. Official Documentation
  144. UDDI
  145. UDDI Resources
  146. XML-RPC
  147. XML-RPC in PHP
  148. Informit Articles and Sample Chapters
  149. Books and e-Books
  150. Official Documentation
  151. Ajax
  152. Asynchronous Javascript
  153. Client-side XSLT
  154. SAJAX and PHP
  155. Ajax Resources
  156. JSON
  157. Ruby on Rails
  158. Creating Objects
  159. Ruby Basics: Arrays and Other Sundry Bits
  160. Ruby Basics: Iterators and Persistence
  161. Starting on the Rails
  162. Rails and Databases
  163. Rails: Ajax and Partials
  164. Rails Resources
  165. Web Services Security
  166. Web Services Security Resources
  167. SAML
  168. Informit Articles and Sample Chapters
  169. Books and e-Books
  170. Specification and Implementation
  171. XML Digital Signatures
  172. XML Digital Signatures Resources
  173. XML Key Management Services
  174. Resources for XML Key Management Services
  175. Internationalization
  176. Resources
  177. Grid Computing
  178. Grid Resources
  179. Web Services Resource Framework
  180. Web Services Resource Framework Resources
  181. WS-Addressing
  182. WS-Addressing Resources
  183. WS-Notifications
  184. New Languages: XML in Use
  185. Informit Articles and Sample Chapters
  186. Books and e-Books
  187. Official Documentation
  188. Google Web Toolkit
  189. GWT Basic Interactivity
  190. Google Sitemaps
  191. Google Sitemaps Resources
  192. Accessibility
  193. Web Accessibility
  194. XML Accessibility
  195. Accessibility Resources
  196. The Semantic Web
  197. Defining a New Ontology
  198. OWL: Web Ontology Language
  199. Semantic Web Resources
  200. Google Base
  201. Microformats
  202. StructuredBlogging
  203. Live Clipboard
  204. WML
  205. XHTML-MP
  206. WML Resources
  207. Google Web Services
  208. Google Web Services API
  209. Google Web Services Resources
  210. The Yahoo! Web Services Interface
  211. Yahoo! Web Services and PHP
  212. Yahoo! Web Services Resources
  213. eBay REST API
  214. WordML
  215. WordML Part 2: Lists
  216. WordML Part 3: Tables
  217. WordML Resources
  218. DocBook
  219. Articles
  220. Books and e-Books
  221. Official Documentation and Implementations
  222. XML Query
  223. Informit Articles and Sample Chapters
  224. Books and e-Books
  225. Official Documentation
  226. XForms
  227. Informit Articles and Sample Chapters
  228. Books and e-Books
  229. Official Documentation
  230. Resource Description Framework (RDF)
  231. Informit Articles and Sample Chapters
  232. Books and e-Books
  233. Official Documentation
  234. Topic Maps
  235. Informit Articles and Sample Chapters
  236. Books and e-Books
  237. Official Documentation, Implementations, and Other Resources
  238. Rich Site Summary (RSS)
  239. Informit Articles and Sample Chapters
  240. Books and e-Books
  241. Official Documentation
  242. Simple Sharing Extensions (SSE)
  243. Atom
  244. Podcasting
  245. Podcasting Resources
  246. Scalable Vector Graphics (SVG)
  247. Informit Articles and Sample Chapters
  248. Books and e-Books
  249. Official Documentation
  250. OPML
  251. OPML Resources
  252. Summary
  253. Projects
  254. JavaScript TimeTracker: JSON and PHP
  255. The Javascript Timetracker
  256. Refactoring to Javascript Objects
  257. Creating the Yahoo! Widget
  258. Web Mashup
  259. Google Maps
  260. Indeed Mashup
  261. Mashup Part 3: Putting It All Together
  262. Additional Resources
  263. Frequently Asked Questions About XML
  264. What's XML, and why should I use it?
  265. What's a well-formed document?
  266. What's the difference between XML and HTML?
  267. What's the difference between HTML and XHTML?
  268. Can I use XML in a browser?
  269. Should I use elements or attributes for my document?
  270. What's a namespace?
  271. Where can I get an XML parser?
  272. What's the difference between a well-formed document and a valid document?
  273. What's a validating parser?
  274. Should I use DOM or SAX for my application?
  275. How can I stop a SAX parser before it has parsed the entire document?
  276. 2005 Predictions
  277. 2006 Predictions
  278. Nick's Book Picks

Mashups, or applications that use data from a number of difference sources -- particularly web services sources -- are all the rage these days, so I thought I'd take a few moments to discuss a service that's not typically used: the eBay API.

eBay, as you probably know, is the world's largest auction site, offering, well, just about anything. (I still can't find a Sony IDC-SX35 Digital Voice Recorder, but maybe that's just me.) From the eBay browser-based interface, you can list items for sale, bid and buy them, and search for specific item, paying a fee to eBay when you sell an item.

eBay also makes it possible to show eBay information outside of the confines of the eBay site. For example, if you were creating a web page that includes information on, say, toy trains, you can add toy trains that are currently for sale. You could also create a page that shows your own auction listings and provides a link back to the eBay site so users can make a bid. In fact, eBay provides a fairly complete SOAP-based web service that enables you to build complete applications for buying and selling on the site.

In this case, however, we're going to start small, creating a simple web page that includes a few items provided by eBay's REST API, which simply enables you to execute a search. Using Java, we'll create the request, parse the XML, and pull out the appropriate information. We'll then use that information to create HTML, which we'll then output first to the command line and then to a web page.

The first step is to create your developer credentials. Execute the following steps:

  1. Go to eBay's developer site and join the developer program.
  2. When you fill out the form, eBay will send you a confirmation email that includes a confirmation code. Check your email and follow the instructions to use that code to generate your application keys.
  3. In order to make requests, you will have to use an eBay account, but when you are creating your application you will actually be working against the "sandbox," a test version of the database. Create a sandbox test account for these requests. (Once your application is complete and you are making requests against the production database, you'll use your "real" eBay account.)
  4. Create an eBay REST API token, which you'll include in your requests. Go to eBay's token tool. Choose "Sandbox" for the environment and enter the keys you received in step 2.

To make sure things are working, try a sample call, such as:

http://rest.api.sandbox.ebay.com/restapi?CallName=GetSearchResults&RequestToken=yourTokenHere&RequestUserId=yourUseridHere&Query=toy%20boat&Schema=1

You should see a result such as figure 1, with an Ack element of Success.


Figure 1: The sample request

Several parameters can come in handy in building your requests:

  • Category: Optional, this defaults to 0, but can be used to limit your search to a particular numeric category code.
  • IncludeSellers: You can use this parameter to limit your search to specific sellers. For example, you could display only your own items. This parameter can include up to 100 comma delimited seller ids.
  • Query: The keywords for your search, with spaces represented by %20. This parameter is limited to 350 characters.
  • EndTimeFrom and EndTimeTo: These parameters enable you to create a time range for items returned by the search.
  • MaxResults: Unless you specify otherwise, the default search returns up to 100 items, but you can use this parameter to specify a set of up to 400 items.
  • Skip: This parameter enables you to create a "pagination" effect, skipping the number of items you'd retrieved in previous calls.
  • Schema: This parameter determines whether you will use the "legacy" API, which will stop functioning June 1, 2006, or the "new" XML API. Set this value to 1 for the new API.
  • TotalOnly: Normally the request returns item information, but if you just want to know how many items would be returned by this search, set this parameter to 1.

You can get a full list of input parameters in the REST API documentation.

As with any REST application, you can most easily test the construction of your requests by entering them in your browser. You should get a response something like:

<?xml version="1.0" encoding="UTF-8"?>

<GetSearchResultsResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2005-12-29T04:55:46.403Z</Timestamp>
  <Ack>Success</Ack>
  <Version>437</Version>

  <Build>e437_core_Bundled_2146580_R1</Build>
  <SearchResultItemArray>
    <SearchResultItem>
      <Item>
        <ItemID>4504295322</ItemID>

        <ListingDetails>
          <StartTime>2005-12-27T14:35:50.000Z</StartTime>
          <EndTime>2006-01-03T14:35:50.000Z</EndTime>
          <ViewItemURL>http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&amp;item=4504295322&amp;category=617&amp;ssPageName=WDVW&amp;rd=1</ViewItemURL>

        </ListingDetails>
        <SellingStatus>
          <BidCount>0</BidCount>
          <CurrentPrice currencyID="USD">15.5</CurrentPrice>
        </SellingStatus>

        <Site>US</Site>
        <Title>Claymation Christmas - Will Vinton New DVD! + Easter!</Title>
        <ListingType>Chinese</ListingType>
        <BuyItNowPrice currencyID="USD">15.95</BuyItNowPrice>

        <Currency>USD</Currency>
        <GiftIcon>0</GiftIcon>
        <SiteHostedPicture>
          <GalleryType>None</GalleryType>

        </SiteHostedPicture>
        <SubTitle></SubTitle>
        <PaymentMethods>PayPal</PaymentMethods>
        <Country>US</Country>

        <Storefront>
          <StoreCategoryID>0</StoreCategoryID>
          <StoreCategory2ID>0</StoreCategory2ID>
          <StoreURL>http://stores.sandbox.ebay.com/id=396492</StoreURL>

          <StoreName>Rover number Five</StoreName>
        </Storefront>
        <PostalCode>98604</PostalCode>
        <ShippingDetails>
          <ShippingType>NotSpecified</ShippingType>

        </ShippingDetails>
        <SearchDetails>
          <BuyItNowEnabled>true</BuyItNowEnabled>
        </SearchDetails>
      </Item>

      <SearchResultValues>Picture</SearchResultValues>
    </SearchResultItem>
    <SearchResultItem>...</SearchResultItem>
  </SearchResultItemArray>
  <ItemsPerPage>100</ItemsPerPage>

  <PageNumber>1</PageNumber>
  <HasMoreItems>false</HasMoreItems>
  <PaginationResult>
    <TotalNumberOfPages>1</TotalNumberOfPages>

    <TotalNumberOfEntries>6</TotalNumberOfEntries>
  </PaginationResult>
  <CategoryArray/>
</GetSearchResultsResponse>

Note the structure of the returned data. At the beginning is information about the search itself, such as the version of the API responding to the call and whether or not the request was successful. (In the case of an error, information as to the cause will be provided in the body of the response.) Next is the SearchResultItemArray, which contains an element for each result. Each resulting item consists of information about the item to be sold, as well as information about the auction itself, such as the number of bids and the current price.

Now let's go ahead and analyze the data using Java.

Start by creating the basic application:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class ShowFile {

   public static void main (String args[]) {

       String requestToken = your token here;
       String requestUserId = your sandbox user ID here;
       String query = args[0];

   }
}

First we're importing the classes we're going to use. The requestToken is the REST API token is the value you retrieved in step 4 above. (Note that it's the REST API token, and not the application token.) The requestUserId is the eBay user ID you created for the sandbox in step 3.

Now create and parse the request:

...
public class ShowFile {

   public static void main (String args[]) {

       String requestToken = your token here;
       String requestUserId = your sandbox user ID here;
       String query = args[0];


       String docString = "http://rest.api.sandbox.ebay.com/restapi?CallName=GetSearchResults"+
             "&RequestToken="+requestToken+
             "&RequestUserId="+requestUserId+
             "&Query="+query+
             "&Schema=1";

       Document doc = null;
       try {
           DocumentBuilderFactory dbf = 
                    DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           doc = db.parse(docString);
       } catch (java.io.IOException e) {
           System.out.println("Can't find the file");
       } catch (Exception e) {
           System.out.print("Problem parsing the file.");
       }

       Element root = doc.getDocumentElement();
       System.out.println("The root element is " + 
                                      root.getNodeName() + ".\n");

   }
}

The actual URL for the request is based on the appropriate host name -- we'll change it to rest.api.ebay.com for production -- and the fact that there's only one allowable REST call, GetSearchResults.

From there we have standard Document Object Model code. First, using the JDK implementation, we create a DocumentBuilder and use it to parse the data found at the URL in the request. Once we have the Document object, we can request the root element to make sure it's working. If you run the application, you should receive output of:

The root element is GetSearchResultsResponse.

Next, make sure that the actual request was successful:

...
       Element root = doc.getDocumentElement();

       Element successElement = 
             (Element)root.getElementsByTagName("Ack").item(0);
       if (successElement.getFirstChild().getNodeValue().equals("Success")) {
          System.out.println("Success!");
       } else {
          System.out.println("The request did not process properly.");
       }
   }
}

Once we have the root element, we can use getElementsByTagName to retrieve the Ack element. Because there's only one, we want the first item in that NodeList, which we then cast as an Element instead of a Node. Once we have the Ack element, we need to check the value of its contents.

Its contents, remember, consist of a child Node -- specifically, a Text Node. We retrieve that first child, get it's nodeValue, and see whether it's the text string Success. If not, we know something's gone wrong with the request. You can, of course, modify the application to return the error, but you can also view the request in your browser to see what the problem is.

Assuming all is well, find out how many results we're dealing with:

...
       Element successElement = 
             (Element)root.getElementsByTagName("Ack").item(0);
       if (successElement.getFirstChild().getNodeValue().equals("Success")) {
          System.out.println("Success!");
      
         NodeList results = 
                 root.getElementsByTagName("SearchResultItemArray");
         Element resultsElement = (Element)results.item(0);
         NodeList resultItems = 
                 resultsElement.getElementsByTagName("SearchResultItem");
         int numberOfResultItems = resultItems.getLength();

         Element paginationResults = 
               (Element)root.getElementsByTagName("PaginationResult").item(0);
         String totalResults = 
               paginationResults.getElementsByTagName("TotalNumberOfEntries")
                                .item(0).getFirstChild().getNodeValue();

        System.out.println("There are "+numberOfResultItems+
               " items in this result, out of a total of "+totalResults+".");

       } else {
          System.out.println("The request did not process properly.");
       }
   }
}

First, we're creating a NodeList out of the SearchResultItem children of the SearchResultItemArray element. (We could also have used getChildNodes() to accomplish this feat.) From there, we can get the length of the list to find out how many items we have.

That tells us how many results were in the current response, but to find out how many results exist in the entire database, we need to get the value of the TotalNumberOfEntries element.

If you were to run this application with an argument of, say "christmas", you should get a result something like:

Success!

There are 6 items in this result, out of a total of 6.

Once we know how many items we're dealing with, we can deal with them, extracting the appropriate information:

...
           NodeList resultItems = 
                 resultsElement.getElementsByTagName("SearchResultItem");
           int numberOfResultItems = resultItems.getLength();

           for (int thisItem = 0; thisItem < numberOfResultItems; thisItem++){

               Element thisItemElement = (Element)resultItems.item(thisItem);
               Element innerElement = 
                   (Element)thisItemElement.getElementsByTagName("Item").item(0);
               Element listingDetailsElement = 
                   (Element)innerElement.getElementsByTagName("ListingDetails").item(0);

               String endTime = 
                   listingDetailsElement.getChildNodes().item(1)
                                        .getFirstChild().getNodeValue();

               String itemURL = 
                    listingDetailsElement.getChildNodes().item(2)
                                         .getFirstChild().getNodeValue();

               Element titleElement = 
                    (Element)innerElement.getElementsByTagName("Title").item(0);
               String titleString = titleElement.getFirstChild().getNodeValue();

               Element sellingStatusElement = 
                    (Element)listingDetailsElement.getNextSibling();
               String bids = 
                    sellingStatusElement.getElementsByTagName("BidCount").item(0)
                                        .getFirstChild().getNodeValue();
               Element currentPriceElement = 
                    (Element)sellingStatusElement.getElementsByTagName("CurrentPrice")
                                                 .item(0);
               String currentPrice = currentPriceElement.getFirstChild().getNodeValue();
               String currency = 
                    currentPriceElement.getAttributeNode("currencyID").getNodeValue();

           }


         Element paginationResults = 
               (Element)root.getElementsByTagName("PaginationResult").item(0);
         String totalResults = 
               paginationResults.getElementsByTagName("TotalNumberOfEntries")
                                .item(0).getFirstChild().getNodeValue();

       } else {
          System.out.println("The request did not process properly.");
       }
   }
}

All of this is standard DOM manipulation. First we retrieve a reference to a specific Item element, and then we use DOM methods such as getChildNodes(), getFirstChild(), and getNextSibling() to retrieve specific pieces of information based on their positions in the XML document.

Finally, create and send the output:

...
               String currentPrice = currentPriceElement.getFirstChild().getNodeValue();
               String currency = 
                    currentPriceElement.getAttributeNode("currencyID").getNodeValue();

               System.out.println(
                    "<a href='"+itemURL+"'>"+titleString+"</a> "+currentPrice
                                         +" ("+currency+") - ends "+endTime+"<br />");
         }


         Element paginationResults = 
               (Element)root.getElementsByTagName("PaginationResult").item(0);
...

If you compile and run the application, it should look something like this:

[nicholaschase@spinel www]$ java ShowFile christmas
<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5322&category=617&ssPageName=WDVW&rd=1'><br />Claym
ation Christmas - Will Vinton New DVD! + Easter!</a> <br />15.5 (USD) - end
s 2006-01-03T14:35:50.000Z<br />
<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5470&category=617&ssPageName=WDVW&rd=1'><br />Red S
kelton's Christmas New DVD! Sealed</a> <br />3.5 (USD) - ends 2006-01-03
T14:41:21.000Z<br />

<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5510&category=617&ssPageName=WDVW&rd=1'><br />Claym
ation Christmas - Will Vinton New DVD! + Easter!</a> <br />15.5 (USD) - end
s 2006-01-03T14:43:09.000Z<br />
<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5665&category=617&ssPageName=WDVW&rd=1'><br />SONIC
 CHRISTMAS BLAST - DVD NEW 4 EPISODES</a> <br />4.95 (USD) - ends
 2006-01-03T14:48:14.000Z<br />

<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5666&category=617&ssPageName=WDVW&rd=1'><br />INSPE
CTOR GADGET SAVES CHRISTMAS NEW DVD 4 EPISODES</a> <br />4.9
5 (USD) - ends 2006-01-03T14:48:14.000Z<br />
<a href='http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item=450429
5679&category=617&ssPageName=WDVW&rd=1'><br />A MAT
TER OF PRINCIPLE ~ NEW DVD CHRISTMAS W/ ALAN ARKIN</a> <br />1
0.95 (USD) - ends 2006-01-03T14:48:49.000Z<br />

Now we have a working application, but it can only access the sandbox, or test database. In order to access the production database, we need to "certify" the application. Time was that the "standard" certification process involved submitting your application for review by eBay, a process that took seven to ten days. That process is still in place, but if you're expecting less than 10,000 calls per month, you can "self-certify" your application and get access to the production database immediately.

To self certify, make sure that your application satisfies the certification requirements, and then fill out the self certification form, providing basic information about your application.

Once you receive your confirmation code, follow the same process you used to retrieve your sandbox keys to get your production keys. Once you have them, go back to the token tool and retrieve tokens for the production environment.

Now try your request with the production URL:

http://rest.api.ebay.com/restapi?CallName=GetSearchResults&RequestToken=yourTokenHere&RequestUserId=yourUseridHere&Query=toy%20boat&Schema=1

You should see results similar to those from the sandbox database, but with a couple of significant differences:

<?xml version="1.0" encoding="UTF-8"?>

<GetSearchResultsResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2005-12-29T16:56:23.790Z</Timestamp>
  <Ack>Success</Ack>
  <Version>439</Version>

  <Build>e439_core_Bundled_2176832_R1</Build>
  <SearchResultItemArray>
    <SearchResultItem>
      <Item>
        <ItemID>7377084130</ItemID>

        <ListingDetails>
          <StartTime>2005-12-24T08:56:34.000Z</StartTime>
          <EndTime>2005-12-29T08:56:34.000Z</EndTime>
          <ViewItemURL>http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=7377084130&category=29564&rd=1</ViewItemURL>

        </ListingDetails>
        <SellingStatus>
          <BidCount>10</BidCount>
          <CurrentPrice currencyID="USD">18.5</CurrentPrice>
        </SellingStatus>

        <Site>US</Site>
        <Title>KOSTA BODA 2005 CHRISTMAS TREE ORNAMENT</Title>
        <ListingType>Chinese</ListingType>
        <Currency>USD</Currency>

        <GiftIcon>0</GiftIcon>
        <SiteHostedPicture>
          <GalleryType>Gallery</GalleryType>
        </SiteHostedPicture>
        <VendorHostedPicture>

          <GalleryURL>http://thumbs.ebay.com/pict/7377084130.jpg</GalleryURL>
          <GalleryType>Gallery</GalleryType>
        </VendorHostedPicture>
        <SubTitle></SubTitle>

        <PaymentMethods>PayPal</PaymentMethods>
        <Country>US</Country>
        <ShippingDetails>
          <ShippingType>Flat</ShippingType>

          <DefaultShippingCost>5.99</DefaultShippingCost>
        </ShippingDetails>
        <SearchDetails>
          <BuyItNowEnabled>false</BuyItNowEnabled>
        </SearchDetails>

      </Item>
      <SearchResultValues>Picture</SearchResultValues>
    </SearchResultItem>
...
  </SearchResultItemArray>
  <ItemsPerPage>100</ItemsPerPage>

  <PageNumber>1</PageNumber>
  <HasMoreItems>true</HasMoreItems>
  <PaginationResult>
    <TotalNumberOfPages>1333</TotalNumberOfPages>

    <TotalNumberOfEntries>133222</TotalNumberOfEntries>
  </PaginationResult>
  <CategoryArray/>
</GetSearchResultsResponse>

First, notice that the production version is different from the sandbox application version. eBay tracks versions based on this number, and requires compatibility up to a particular version number at any given time. Second, notice that a large percentage of "live" items also include photos. We can conditionally add this information to the application:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class ShowFile {

   public static void main (String args[]) {

       String requestToken = your token here;
       String requestUserId = your actual eBay ID here;

       String query = args[0];

       String docString = "http://rest.api.ebay.com/restapi?CallName=GetSearchResults"+
             "&RequestToken="+requestToken+
             "&RequestUserId="+requestUserId+
             "&Query="+query+
             "&Schema=1";

       Document doc = null;
       try {
           DocumentBuilderFactory dbf = 
                    DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           doc = db.parse(docString);
       } catch (java.io.IOException e) {
           System.out.println("Can't find the file");
       } catch (Exception e) {
           System.out.print("Problem parsing the file.");
       }

       Element root = doc.getDocumentElement();
       Element successElement = 
             (Element)root.getElementsByTagName("Ack").item(0);
       if (successElement.getFirstChild().getNodeValue().equals("Success")) {
      
           NodeList results = 
                 root.getElementsByTagName("SearchResultItemArray");
           Element resultsElement = (Element)results.item(0);
           NodeList resultItems = 
                 resultsElement.getElementsByTagName("SearchResultItem");
           int numberOfResultItems = resultItems.getLength();

           if (numberOfResultItems > 3){
               numberOfResultItems = 3;
           }

           for (int thisItem = 0; thisItem < numberOfResultItems; thisItem++){

               Element thisItemElement = (Element)resultItems.item(thisItem);
               Element innerElement = 
                   (Element)thisItemElement.getElementsByTagName("Item").item(0);
               Element listingDetailsElement = 
                   (Element)innerElement.getElementsByTagName("ListingDetails").item(0);

               String endTime = 
                   listingDetailsElement.getChildNodes().item(1)
                                        .getFirstChild().getNodeValue();

               String itemURL = 
                    listingDetailsElement.getChildNodes().item(2)
                                         .getFirstChild().getNodeValue();

               Element titleElement = 
                    (Element)innerElement.getElementsByTagName("Title").item(0);
               String titleString = titleElement.getFirstChild().getNodeValue();

               Element sellingStatusElement = 
                    (Element)listingDetailsElement.getNextSibling();
               String bids = 
                    sellingStatusElement.getElementsByTagName("BidCount").item(0)
                                        .getFirstChild().getNodeValue();
               Element currentPriceElement = 
                    (Element)sellingStatusElement.getElementsByTagName("CurrentPrice")
                                                 .item(0);
               String currentPrice = currentPriceElement.getFirstChild().getNodeValue();
               String currency = 
                    currentPriceElement.getAttributeNode("currencyID").getNodeValue();


               String pictureURL = "nopicture.gif";
               NodeList pictureElements = 
                         innerElement.getElementsByTagName("VendorHostedPicture");
               if (pictureElements.getLength() > 0){
                    NodeList pictures = ((Element)pictureElements.item(0))
                                            .getElementsByTagName("GalleryURL");
                    if (pictures.getLength() > 0) {
                        pictureURL = ((Element)pictures.item(0)).getFirstChild().getNodeValue();
                    }
               }

               System.out.println(
                    ">a href='"+itemURL+"'>>img src='"+pictureURL+"' border='0' />>br />"+
                              titleString+">/a> >br />"+currentPrice
                              +" ("+currency+") - ends "+endTime+">br />");
         }

       } else {
          System.out.println("The request did not process properly.");
       }
   }
}

First off, notice that you need to use the production information for the request. Second, while we can limit the number of responses right in the request -- and, in fact, for bandwidth reasons this is the preferred way of handling it -- we can also limit the number of items returned by the application. Finally, we're creating a URL for the thumbnail, starting with a default image if no image is provided. From there we look for the VendorHostedPicture element, which may not actually be there. If, however, it is there, we look for the GalleryURL element, and if it's present, set the pictureURL to the value of it's text node child. Whatever this value works out to be, we're adding it to an img in the response. Now if we run the application, we should see a response similar to:

[nicholaschase@spinel www]$ java ShowFile christmas
<a href='http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=6466664912&category=309&rd=1'><img src='nopicture.gif' border='0' /><br />Touched by an Angel - A Christmas Miracle (1997, VHS)</a> <br />1.99 (USD) - ends 2005-12-29T08:50:22.000Z<br />
<a href='http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=5649127337&category=3488&rd=1'><img src='nopicture.gif' border='0' /><br />L089 Senegal Christmas, Noel Luxury Proof Imperf.</a> <br />19.99 (USD) - ends 2005-12-29T08:50:27.000Z<br />

<a href='http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=8245629512&category=113339&rd=1'><img src='https://thumbs.ebay.com/pict/8245629512.jpg' border='0' /><br />Wedding/Holiday/Christmas White Rose Pew Bows Set of 12</a> <br />8.95 (USD) - ends 2005-12-29T08:50:33.000Z<br />

You can add this output to a web page by converting this application to a servlet or JSP. If that's not an option for you -- say, if you are on a shared hosting plan, as I am -- you can also add the output to a PHP page using the passthru function:

<html>
<head><title>EBay Information</title></head>
<body>
<?php

passthru("/usr/local/java/bin/java -cp /home/nicholaschase/www ShowFile christma
s");
?>
</body>
</html>

The end result is a page similar to figure 2:

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.