Searching in an XML File


You can search for a value in an XML file using the methods that the DefaultHandler and XMLReader interfaces provide. Listing 13-2 shows the ProductsSearch.java application that searches for a specific value in the specified XML file. First, you extend the DefaultHandler class through the ProductsSearch class. The startDocument() method contains statements that prompt the end user to enter the product number. The characters() method contains statements that display information such as the product id, name, and product number for the matching product in the console.

Listing 13-2: Searching in an XML file

image from book
      import java.io.*;      import javax.xml.parsers.SAXParserFactory;      import javax.xml.parsers.SAXParser;      import org.xml.sax.*;      import org.xml.sax.helpers.*;      public class ProductsSearch extends DefaultHandler      {        String key = null;        String currentTagName = null;        String productNumber = null;        String productID = null;        String name= null;        int flag = 0;        public static void main(String[] args) throws Exception        {          System.out.println("Start of Products...");          ProductsSearch readerObj = new ProductsSearch();          readerObj.read(args[0]);        }        public void read(String fileName) throws Exception        {           XMLReader reader =           XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");          reader.setContentHandler(this);          reader.parse(fileName);        }        public void startDocument() throws SAXException        {          System.out.println("Start document");          InputStreamReader istream = new InputStreamReader(System.in);          BufferedReader bufRead = new BufferedReader(istream);          System.out.print("Enter the Product Number:");          try          {           key = bufRead.readLine();          }          catch (IOException e){ }          if (key.length() == 0)          {           System.out.println("No Product Number is entered");           System.exit(0);          }      }      public void endDocument() throws SAXException      {        if (flag == 0)         System.out.println("No matching entry found...");        System.out.println("End document");        }        public void startElement(String uri, String name, String qName, Attributes atts)        {         currentTagName = qName;        }        public void endElement(String uri, String name, String qName)        {}        public void characters(char ch[], int start, int length)        {          String value = new String(ch, start, length);          if (productID  == null && currentTagName.equals("ProductID"))          {           productID = value;          }          if (name == null && currentTagName.equals("Name"))          {           name = value;          }          if (currentTagName.equals("ProductNumber"))           {            if (key.equals(value))            {              System.out.println("*******");              System.out.println("Product ID:" + productID);              System.out.println("Product Name:" + name);              System.out.println("Product Number:" + key);              System.out.println("*******");              flag = 1;            }          }          if (currentTagName.equals("Product"))          {            productID = null;            name = null;            productNumber = null;          }        }       } 
image from book

In the previous code, you set the name of the current element in a private variable named currentTagName, which is used later inside the characters() method.

You actually compare the entered product number with the <ProductNumber> elements in the Products.xml file in the characters() method. Note that the sequence of the elements contained in the <Product> element is very important to enable the matching code to generate the desired results. To get the desired search output based on the product number, you need to ensure that the <ProductNumber> element is the last element inside each of the <Product> elements in the Products.xml file.

Figure 13-2 shows the console window that prompts the user to enter the product number to be searched.

image from book
Figure 13-2

In this case, I entered the product number BE-2908. The output is shown in Figure 13-3.

image from book
Figure 13-3

The previous figure shows the details of the product that has the product number BE-2908.




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net