dhananjay
dhananjay

Reputation: 331

How to get data with tag name & their values inside parent tag in xml

I am working on Java. I am parsing an xml file, I am getting tag values, it is working. I have xml file as follows:

  <DOC>
  <STUDENT>
  <ID>1</ID>
  <NAME>DAN</NAME>
  <ADDRESS>U.K</ADDRESS> 
  </STUDENT>
  <STUDENT>
  <ID>2</ID>
  <NAME>JACK</NAME>
  <ADDRESS>U.S</ADDRESS> 
  </STUDENT>
  </DOC>

I have question that I want to fetch data inside <DOC>....</DOC> with their tag name & value as well. Means I want data as follows:

 "<STUDENT> 
  <ID>1</ID>
  <NAME>DAN</NAME>
  <ADDRESS>U.K</ADDRESS> 
  </STUDENT>
  <STUDENT>
  <ID>2</ID>
  <NAME>JACK</NAME>
  <ADDRESS>U.S</ADDRESS> 
  </STUDENT>"

Please guide me how to do it.

Upvotes: 0

Views: 1278

Answers (2)

Logan
Logan

Reputation: 2505

Take a look at SAX Parser.

This link might be helpful too: http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

Upvotes: 0

rhinds
rhinds

Reputation: 10043

The most common approaches in Java are to use one of either SAX or Dom parsing libraries.

If you look them up you should find loads of documentation/tutorials about them.

Dom is the easiest to use normally as it stores the entire XML in memory and you cna then access any tag, however, this is less performant and can be problematic if you are using very large XML. SAX requires more work, but reads the XML and processes each tag as it gets to it.

Both are able to do what you need though.

Upvotes: 1

Related Questions