0

I have an XML file which I wrote that looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Library name="StreetCorner">
    <Book name="HarryPotter">
        <Author name="JKRowling"/>
    </Book>
    <Book name="SherlockHolmes">
        <Author name="SirAConandoyle"/>
    </Book>
    <Book name="AngelsAndDemons">
        <Author name="DanBrown"/>
    </Book>
</Library>

What is the simplest way to read this?

I need to get the Library name, and all the books in that library, and name of the author who wrote that book.

I already have a model called Library so if I can extract the data with each parse, I can set the values onto a Library object.

name is an attribute of each element in my xml.

  • jaxb is probably the simplest but your really need to position yourself to , is this quick use SAX or do you need to edit maintain the xml then DOM jaxb – Kenneth Clark Nov 26 '14 at 12:08
  • I need to get the data from an XML into an object array. And then re-write into the XML from the object array. I can do the writing easily so I'd prefer to use a simple way of reading as well. –  Nov 26 '14 at 12:13
  • Take a look at this post, http://stackoverflow.com/questions/19371587/reading-xml-document-using-jaxb working with jaxb – Kenneth Clark Nov 26 '14 at 12:24

4 Answers4

1

One way of getting information out of XML file in Java is to use Java XML DOM parser.

You start with:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);

And then access the loaded data:

Element root = document.getDocumentElement();
root.getElementsByTagName("Book")

You can find a full tutorial here. The biggest disadventage of this approach is the fact that you load the whole document into the memory, but it's not an issue in your case.

Other built-in options include:

  • SAX parser
  • JAXP

You can find a detailed description of these options in this document. Even more options are discussed in this question.

Community
  • 1
  • 1
atok
  • 5,880
  • 3
  • 33
  • 62
  • Thanks. I've been going through DOM parser tutorials. Notice my XML looks like this: ``. Do you think it's better to avoid data stored in attribute style? ie. make it look like this instead: `HarryPotter` –  Nov 26 '14 at 12:31
  • Avoiding attributes leads to huge XML structures, they are unavoidable. – atok Nov 26 '14 at 14:10
1

You could try using a mapping library. Simple XML will automatically parse your XML and place in Java objects. You just have to mark up your objects with annotations.

markbernard
  • 1,412
  • 9
  • 18
1

Here is a simple way to read your xml using JAXB

Test runner class

public class XmlTest
{
  public static void main(String[] args)
  {
    try
    {
      File file = new File("d:\\file.xml");
      JAXBContext jaxbContext = JAXBContext.newInstance(Library.class);

      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
      Library library = (Library) jaxbUnmarshaller.unmarshal(file);

      for (Book book : library.getBookList())
      {
        System.out.println(book.getName());
      }
    }
    catch (JAXBException e)
    {
      e.printStackTrace();
    }

  }
}

Book class

@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Book
{
  @XmlAttribute(name = "name")
  private String name;

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }
}

Library class

@XmlRootElement(name = "Library")
@XmlAccessorType(XmlAccessType.FIELD)
public class Library
{
  @XmlAttribute(name = "name")
  private String name;

  @XmlElement(name = "Book")
  private List<Book> bookList;

  public List<Book> getBookList()
  {
    return bookList;
  }

  public void setBookList(List<Book> bookList)
  {
    this.bookList = bookList;
  }

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }
}

Xml writer

public class XMlWriter
{
  public static void main(String[] args)
  {
    ArrayList<Book> bookArrayList = new ArrayList<Book>();
    Book myNewBook = new Book();
    myNewBook.setName("My First Copy");
    bookArrayList.add(myNewBook);

    Library library = new Library();
    library.setName("My Name");
    library.setBookList(bookArrayList);

    try
    {
      JAXBContext jaxbContext = JAXBContext.newInstance(Library.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      try
      {
        jaxbMarshaller.marshal(library, new FileOutputStream("D:\\file2.xml"));
      }
      catch (FileNotFoundException e)
      {
        e.printStackTrace();
      }
      jaxbMarshaller.marshal(library, System.out);
    }
    catch (JAXBException e)
    {
      e.printStackTrace();
    }
  }
}

The following references used

reading xml document using jaxb

http://www.mkyong.com/java/jaxb-hello-world-example/

*note THIS IS NOT the way to do exception handling

Community
  • 1
  • 1
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26
0

I would recommend using Xpath. Xpath can be used to get all the elements of together e.g. in your case you can get all the books or you can get the first book and loop through it.

Here is a good tutorial about it from Tutorialspoint.com: http://www.w3schools.com/xpath/xpath_examples.asp

Suri
  • 66
  • 6