[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Java code to read XML document

Posted on 2011-04-18
11
Medium Priority
?
772 Views
Last Modified: 2012-05-11
I am tyring to update the readProducts method so that is reads from the products.xml file but it wont compile.

these are the errors:
C:\Documents and Settings\ethatc001\My Documents\Murach\Java6\Exercises\java1.6\ch20\XMLTester\XMLTesterApp.java:49: cannot find symbol
symbol  : method hasnext()
location: interface javax.xml.stream.XMLStreamReader
        while (reader.hasnext())
                     ^
C:\Documents and Settings\ethatc001\My Documents\Murach\Java6\Exercises\java1.6\ch20\XMLTester\XMLTesterApp.java:52: cannot find symbol
symbol  : variable eventtype
location: class XMLTesterApp
                  switch (eventtype)
                          ^
C:\Documents and Settings\ethatc001\My Documents\Murach\Java6\Exercises\java1.6\ch20\XMLTester\XMLTesterApp.java:60: cannot find symbol
symbol  : method setcode(java.lang.String)
location: class Product
                              p.setcode(code);
                               ^
3 errors


Here is the code:
import java.util.ArrayList;
import java.io.*;
import javax.xml.stream.*;  // StAX API

public class XMLTesterApp
{
    private static String productsFilename = "products.xml";

    public static void main(String[] args)
    {
        System.out.println("Products list:");
        ArrayList<Product> products = readProducts();
        printProducts(products);

/*
        Product p1 = new Product("test", "XML Tester", 77.77);
        products.add(p1);
        writeProducts(products);
        System.out.println("XML Tester has been added to the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

/*
        products.remove(2);
        writeProducts(products);
        System.out.println("XML Tester has been deleted from the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

    }

    private static ArrayList<Product> readProducts()
    {
        ArrayList<Product> products = new ArrayList<Product>();
        Product p = null;

        // add code that reads the XML document from the products.xml file
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        FileReader fileReader = new FileReader("products.xml");
        XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);


        while (reader.hasnext())
        {
                  int eventType = reader.getEventType();
                  switch (eventtype)
                  {
                        case XMLStreamConstants.START_ELEMENT:
                        String elementName = reader.getLocalName();
                        if (elementName.equals ("Product"))
                        {
                              p = new Product();
                              String code = reader.getAttributeValue(0);
                              p.setcode(code);
                        }
                        if (elementName.equals("Description"))
                        {
                              String description = reader.getElementText();
                              p.setDescription(description);
                        }
                        if (elementName.equals("Price"))
                        {
                              String priceString = reader.getElementText();
                              double price = Double.parseDouble(priceString);
                              p.setPrice(price);
                        }
                        break;
                        case XMLStreamConstants.END_ELEMENT:
                        elementName = reader.getLocalName();
                        if (elementName.equals("Product"))
                        {
                              products.add(p);
                        }
                        break;
                        default:
                        break;
                  }
                  reader.next();
            }
          return products;
    }

    private static void writeProducts(ArrayList<Product> products)
    {
        // add code that writes the XML document to the products.xml file
    }

    private static void printProducts(ArrayList<Product> products)
    {
        for (Product p : products)
        {
            printProduct(p);
        }
        System.out.println();
    }

    private static void printProduct(Product p)
    {
        String productString =
            StringUtils.padWithSpaces(p.getCode(), 8) +
            StringUtils.padWithSpaces(p.getDescription(), 44) +
            p.getFormattedPrice();

        System.out.println(productString);
    }
}
0
Comment
Question by:edthatcher
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35420442
usually hasNext()  upper case Next
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35420452
susually setCode() upper case Code
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35420461
and perhaps eventType - upper catse Type
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 47

Expert Comment

by:for_yan
ID: 35420484
I don't have class Product to test

but hasnext() and evetType() I was right;

secode() is your own method from Product, so
you know better
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35420487
Post Product class if you want me to check it more
0
 
LVL 3

Expert Comment

by:JChrison
ID: 35420507
switch (eventtype) Should be  switch (eventType)
0
 
LVL 3

Expert Comment

by:JChrison
ID: 35420519
and method hasnext() should be hasNext()
0
 
LVL 92

Expert Comment

by:objects
ID: 35420522
try this:


public class XMLTesterApp
{
    private static String productsFilename = "products.xml";

    public static void main(String[] args)
    {
        System.out.println("Products list:");
        ArrayList<Product> products = readProducts();
        printProducts(products);

/*
        Product p1 = new Product("test", "XML Tester", 77.77);
        products.add(p1);
        writeProducts(products);
        System.out.println("XML Tester has been added to the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

/*
        products.remove(2);
        writeProducts(products);
        System.out.println("XML Tester has been deleted from the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

    }

    private static ArrayList<Product> readProducts()
    {
        ArrayList<Product> products = new ArrayList<Product>();
        Product p = null;

        // add code that reads the XML document from the products.xml file
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        FileReader fileReader = new FileReader("products.xml");
        XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);


        while (reader.hasNext())
        {
                  int eventType = reader.getEventType();
                  switch (eventType)
                  {
                        case XMLStreamConstants.START_ELEMENT:
                        String elementName = reader.getLocalName();
                        if (elementName.equals ("Product"))
                        {
                              p = new Product();
                              String code = reader.getAttributeValue(0);
                              p.setCode(code);
                        }
                        if (elementName.equals("Description"))
                        {
                              String description = reader.getElementText();
                              p.setDescription(description);
                        }
                        if (elementName.equals("Price"))
                        {
                              String priceString = reader.getElementText();
                              double price = Double.parseDouble(priceString);
                              p.setPrice(price);
                        }
                        break;
                        case XMLStreamConstants.END_ELEMENT:
                        elementName = reader.getLocalName();
                        if (elementName.equals("Product"))
                        {
                              products.add(p);
                        }
                        break;
                        default:
                        break;
                  }
                  reader.next();
            }
          return products;
    }

    private static void writeProducts(ArrayList<Product> products)
    {
        // add code that writes the XML document to the products.xml file
    }

    private static void printProducts(ArrayList<Product> products)
    {
        for (Product p : products)
        {
            printProduct(p);
        }
        System.out.println();
    }

    private static void printProduct(Product p)
    {
        String productString =
            StringUtils.padWithSpaces(p.getCode(), 8) +
            StringUtils.padWithSpaces(p.getDescription(), 44) +
            p.getFormattedPrice();

        System.out.println(productString);
    }
}

0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35420536
This compiles with some Product stub


import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.io.*;
import javax.xml.stream.*;  // StAX API

public class XMLTesterApp
{
    private static String productsFilename = "products.xml";

    public static void main(String[] args)
    {
        System.out.println("Products list:");
        ArrayList<Product> products = readProducts();
        printProducts(products);

/*
        Product p1 = new Product("test", "XML Tester", 77.77);
        products.add(p1);
        writeProducts(products);
        System.out.println("XML Tester has been added to the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

/*
        products.remove(2);
        writeProducts(products);
        System.out.println("XML Tester has been deleted from the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

    }

    private static ArrayList<Product> readProducts()
    {
        ArrayList<Product> products = new ArrayList<Product>();
        Product p = null;

        try {

        // add code that reads the XML document from the products.xml file
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        FileReader fileReader = new FileReader("products.xml");
        XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);


        while (reader.hasNext())
        {
                  int eventType = reader.getEventType();
                  switch (eventType)
                  {
                        case XMLStreamConstants.START_ELEMENT:
                        String elementName = reader.getLocalName();
                        if (elementName.equals ("Product"))
                        {
                              p = new Product();
                              String code = reader.getAttributeValue(0);
                              p.setCode(code);
                        }
                        if (elementName.equals("Description"))
                        {
                              String description = reader.getElementText();
                              p.setDescription(description);
                        }
                        if (elementName.equals("Price"))
                        {
                              String priceString = reader.getElementText();
                              double price = Double.parseDouble(priceString);
                              p.setPrice(price);
                        }
                        break;
                        case XMLStreamConstants.END_ELEMENT:
                        elementName = reader.getLocalName();
                        if (elementName.equals("Product"))
                        {
                              products.add(p);
                        }
                        break;
                        default:
                        break;
                  }
                  reader.next();
            }
         
    }  catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }
         return products;
    }

    private static void writeProducts(ArrayList<Product> products)
    {
        // add code that writes the XML document to the products.xml file
    }

    private static void printProducts(ArrayList<Product> products)
    {
        for (Product p : products)
        {
            printProduct(p);
        }
        System.out.println();
    }

    private static void printProduct(Product p)
    {
        String productString =
            StringUtils.padWithSpaces(p.getCode(), 8) +
            StringUtils.padWithSpaces(p.getDescription(), 44) +
            p.getFormattedPrice();

        System.out.println(productString);
    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35420603

This is similar to above, but padWithSpaces() replaced by rightPad() method
and Product stub is attached below

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.io.*;
import javax.xml.stream.*;  // StAX API

public class XMLTesterApp
{
    private static String productsFilename = "products.xml";

    public static void main(String[] args)
    {
        System.out.println("Products list:");
        ArrayList<Product> products = readProducts();
        printProducts(products);

/*
        Product p1 = new Product("test", "XML Tester", 77.77);
        products.add(p1);
        writeProducts(products);
        System.out.println("XML Tester has been added to the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

/*
        products.remove(2);
        writeProducts(products);
        System.out.println("XML Tester has been deleted from the XML document.\n");
*/

        System.out.println("Products list:");
        products = readProducts();
        printProducts(products);

    }

    private static ArrayList<Product> readProducts()
    {
        ArrayList<Product> products = new ArrayList<Product>();
        Product p = null;

        try {

        // add code that reads the XML document from the products.xml file
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        FileReader fileReader = new FileReader("products.xml");
        XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);


        while (reader.hasNext())
        {
                  int eventType = reader.getEventType();
                  switch (eventType)
                  {
                        case XMLStreamConstants.START_ELEMENT:
                        String elementName = reader.getLocalName();
                        if (elementName.equals ("Product"))
                        {
                              p = new Product();
                              String code = reader.getAttributeValue(0);
                              p.setCode(code);
                        }
                        if (elementName.equals("Description"))
                        {
                              String description = reader.getElementText();
                              p.setDescription(description);
                        }
                        if (elementName.equals("Price"))
                        {
                              String priceString = reader.getElementText();
                              double price = Double.parseDouble(priceString);
                              p.setPrice(price);
                        }
                        break;
                        case XMLStreamConstants.END_ELEMENT:
                        elementName = reader.getLocalName();
                        if (elementName.equals("Product"))
                        {
                              products.add(p);
                        }
                        break;
                        default:
                        break;
                  }
                  reader.next();
            }
         
    }  catch(Exception ex){
            System.out.println("error " + ex.toString());
            ex.printStackTrace();
        }
         return products;
    }

    private static void writeProducts(ArrayList<Product> products)
    {
        // add code that writes the XML document to the products.xml file
    }

    private static void printProducts(ArrayList<Product> products)
    {
        for (Product p : products)
        {
            printProduct(p);
        }
        System.out.println();
    }

    private static void printProduct(Product p)
    {
        String productString =
            StringUtils.rightPad(p.getCode(), 8) +
            StringUtils.rightPad(p.getDescription(), 44) +
            p.getFormattedPrice();

        System.out.println(productString);
    }
}

class Product{
    public void setCode(String s){

    }
      public void setDescription(String s){

    }
        public void setPrice(double d){

    }

      public String getCode(){
          return null;

    }
       public String getDescription(){
                return null;
    }

    public double getFormattedPrice(){
          return 0.0;
    }
}

Open in new window

0
 

Author Closing Comment

by:edthatcher
ID: 35420924
thank you
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month18 days, 16 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question