Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Claude Carter   on Jul 03 In Java Category.

  
Question Answered By: Yvette Griffin   on Jul 03

You should use dom parser and node. Here I paste the example, please copy to a
notepad to view.

XML File
<book> <person> <first>Kiran</first> <last>Pai</last> <age>22</age>
</person> <person> <first>Steve</first> <last>Jobs</last> <age>40</age>
</person> </book>

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadAndPrintXMLFile{

public static void main (String argv []){
try {

DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));

System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());


NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);

for(int s=0; s<listOfPersons.getLength() ; s++){


Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode;

Element firstNameElement = (Element)firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());

Element lastNameElement = (Element)lastNameList.item(0);

NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());

Element ageElement = (Element)ageList.item(0);

NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " +
((Node)textAgeList.item(0)).getNodeValue().trim());
}

}

}catch (Exception err) {
err.printStackTrace ();
}
}

Share: 

 

This Question has 5 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on XML with java Or get search suggestion and latest updates.


Tagged: