0

Possible Duplicate:
What is the best/simplest way to read in an XML file in Java application?

I have an xml like this:

<Root>
   <Commodity>
       <Which name="Book" />
       <Book name="harley" price="5" />
       <Book name="Marley" price="8" />
       <Book name="hampi" price="10" />
   </Commodity>
   <Item>
      <Commodity>
         <Which name="fiction" />
         <Book name="harley" price="5" />
         <Book name="Marley" price="8" />
         <Book name="hampi" price="10" />
      </Commodity>
      <Item>
         <Commodity>
            <Which name="thriller" />
            <Book name="hjhj" price="5" />
            <Book name="ccvcv" price="8" />
            <Book name="vcvnnn" price="10"/>
         </Commodity>
      </Item>
   </Item>
</Root>

I feel that this is a pretty complex xml structure since it has a nested tag. is there a way around to generate java class for the structure?

Community
  • 1
  • 1
Parameswar
  • 1,951
  • 9
  • 34
  • 57

3 Answers3

3

If you have an XSD or DTD, you can easily create a representation of a document using JAXB.

If you don't have a schema definition, I recommend writing it. It's gonna come in handy soon enough anyway. As soon as you try to validate documents or share your format with anyone.

BTW, this is NOT a complicated XML document ;)

toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
1

While I completely agree with @Tom on the necessity of a schema, sometimes it's an overkill. You can use a fast and simple OXM framework like XStream. see http://x-stream.github.io/

facundofarias
  • 2,973
  • 28
  • 27
Gergely Szilagyi
  • 3,813
  • 1
  • 14
  • 12
0

Note that XSD (or other schemas) only provides constraints on direct children. So it it not clear whether you have only two levels of nesting for Item or infinite. If the former you will have to write code manually - schemas won't do it for you.

Deducing schemas from a corpus of documents is a very hard task.

I'd also comment that the nested use of Item is not likely to be a useful way of indicating multiple properties for an Item.

peter.murray.rust
  • 37,407
  • 44
  • 153
  • 217