I want to get the value of the middle name from the below XML in JAVA.
<employee>
<emp1 name='firstName'>FNAme</emp1>
<emp1 name='middleName'>MNAme</emp1>
<emp1 name='LastName'>LNAme</emp1>
</employee>
this work for me pretty well:
java code
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class main
{
public static void main(String[] args) {
try {
File file = new File(".idea/company.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
System.out.println("Root Element :" + document.getDocumentElement().getNodeName());
NodeList nList = document.getElementsByTagName("employee");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Middle Name : " + eElement.getElementsByTagName("middleName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
}
}
}
catch(IOException | ParserConfigurationException | SAXException e) {
System.out.println(e);
}
the xml look like this:
<?xml version="1.0"?>
<company>
<employee>
<firstName>FNAme</firstName>
<middleName>MNAme</middleName>
<lastName>LNAme</lastName>
</employee>
</company>
Related
input XML file
<ContactD>
<addr>
<name>jack</name>
<street>south street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716</pin>
</addr>
<addr>
<name>Benjamin</name>
<street>north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
The output should like this:
<ContactD>
<addr>
<name>jack,Benjamin</name>
<street>south street,north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716,621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
I tried using Java code I tried to match the state element after that I don't how to concatenate those two into one
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class Jparser {
private static final String FILENAME = "books.xml";
public static void main(String[] args) {
// Instantiate the Factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// optional, but recommended
// process XML securely, avoid attacks like XML External Entities (XXE)
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// parse XML file
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(FILENAME));
// optional, but recommended
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("addr");
String[] hell= new String[3];
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String name = element.getElementsByTagName("name").item(0).getTextContent();
String street = element.getElementsByTagName("street").item(0).getTextContent();
hell[temp]= element.getElementsByTagName("state").item(0).getTextContent();
String country = element.getElementsByTagName("country").item(0).getTextContent();
String pin = element.getElementsByTagName("pin").item(0).getTextContent();
System.out.println("Current Element :" + node.getNodeName());
System.out.println("name : " + name);
System.out.println("street : " + street);
System.out.println("state : " + hell[temp]);
System.out.println("country : " + country);
System.out.printf("pin :"+ pin);
}
}
for (int t = 0; t < list.getLength()-1; t++) {
if(hell[t].equals(hell[t+1])) {
/////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
System.out.println("same");
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
I got stuck when I tried to contact that two element node which I identified as the same into one...I finished up matching those state nodes...need help for concatenation!!
input
<ContactD>
<addr>
<name>jack</name>
<street>south street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716</pin>
</addr>
<addr>
<name>Benjamin</name>
<street>north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
<addr>
<name>yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
Expected output :
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ContactD>
<addr>
<name>jack,Benjamin</name>
<street>south street,north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716,621706</pin>
</addr>
<addr>
<name>Ryan,yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
Javacode for this concatenation is below : (sorry for too many reduntant comments and uneven code)
import java.io.File;
// j a v a 2 s .co m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.io.IOException;
public class Jparser {
private static final String FILENAME = "books.xml";
private static void toString(Document newDoc) throws Exception{
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(newDoc);
Result dest = new StreamResult(new File("books.xml"));
aTransformer.transform(src, dest);
}
public static void main(String[] args) throws Exception {
// Instantiate the Factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// optional, but recommended
// process XML securely, avoid attacks like XML External Entities (XXE)
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// parse XML file
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(FILENAME));
// optional, but recommended
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("addr");
//String[] hell= new String[10];
ArrayList<String> hell = new ArrayList<String>();
ArrayList<Element> Ements = new ArrayList<Element>();
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Ements.add(element);
String name = element.getElementsByTagName("name").item(0).getTextContent();
String street = element.getElementsByTagName("street").item(0).getTextContent();
hell.add(element.getElementsByTagName("state").item(0).getTextContent());
String country = element.getElementsByTagName("country").item(0).getTextContent();
String pin = element.getElementsByTagName("pin").item(0).getTextContent();
System.out.println("Current Element :" + node.getNodeName());
System.out.println("name : " + name);
System.out.println("street : " + street);
System.out.println("state : " + hell.get(temp));
System.out.println("country : " + country);
System.out.printf("pin :"+ pin);
}
}
System.out.println("The size of the ArrayList is: " + Ements.size());
// System.out.println(Ements.get(0).name);
for (int t = 0; t < Ements.size()-1; t++) {
// for(int s=1;s<Ements.size()-1;s++) {
//for(int d=1; d<list.getLength()-1;d++) {
if(hell.get(t).equals(hell.get(t+1))) {
/////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
// int z=t;
String[] he= {"name","street","state","country","pin"};
for(int a=0; a<he.length; a++) {
//System.out.printf(Ements.get[a]);
String zz0=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent();
String zz1=Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
if(!zz0.equals(zz1)){
Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz0+","+zz1);
}
//String zz=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent()+","+Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
// Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz);
// System.out.println(Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent());
}
doc.getDocumentElement().removeChild(Ements.get(t+1));
Ements.remove(t+1);
hell.remove(t+1);
System.out.println(Ements.size());
}
}
System.out.println(Ements.size());
// DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
//Document newDoc = domBuilder.newDocument();
//Element rootElement = newDoc.createElement("parent");
// NodeList toremove=doc.getDocumentElement().getChildNodes();
//for(int i=0;i<toremove.getLength();i++) {
// doc.getDocumentElement().removeChild(toremove.item(i));
//}
//doc.getDocumentElement().appendChild(Ements.get(0));
//doc.getDocumentElement().appendChild(Ements.get(1));
toString(doc);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
If I switch it to xml it works fine but to kml nothing. thought it was basically the same thing,probably missing something silly, or messed it up completly sorry for inconvience but help is much appreciated. basically just trying to read a kml file data on java.
package mysqlcon;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:/Users/D/Desktop/mysql/mappedv.kml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("mappedv");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("coordinates : " + eElement.getElementsByTagName("coordinates").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have an xml file in the following pattern which contains a few Complex Empty Elements(elements with no content, only attributes).
<items>
<item id="0" name="a" />
<item id="1" name="b" />
</items>
I'm at lose to parse the attributes from them. This is what I have done so far :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
Element itemsElement = document.getDocumentElement();
if (itemsElement.getTagName().equals(TAG_ITEMS)) {
NodeList nodeList = itemsElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
// process each item node
Node node = nodeList.item(i);
if (node.getNodeType() == Node.TEXT_NODE) { // Is this the right way?
Text text = (Text) node;
// Do stuff with attributes
}
}
}
I cannot cast these Text nodes to Element nodes and get attributes, I cannot get attributes from node using getAttributes - NPE at NamedNodeMap attributes.getLength(), I cannot cast it to Text and get attributes. How can I parse the attributes?
You are not interested in the text context of the nodes inside of items but in the attributes of the nodes item. you could proceed as follow:
//process each item node
Node node = nodeList.item(i);
if (node.getNodeName().equals("item")) {
NamedNodeMap attributes = node.getAttributes();
System.out.printf("id=%s, name=%s%n",
attributes.getNamedItem("id").getTextContent(),
attributes.getNamedItem("name").getTextContent());
}
This would print:
id=0, name=a
id=1, name=b
Assuming you want to get the indiviudal attributes of the nodes you need to one of two things (or both depending on your needs)...
You need to test if the current node is an ELEMENT_NODE or if the current node's name is equal to item (assuming all the node names are the same), for example...
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class Test {
public static final String TAG_ITEMS = "items";
public static void main(String[] args) {
try (InputStream is = Test.class.getResourceAsStream("/Test.xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
Element itemsElement = document.getDocumentElement();
if (itemsElement.getTagName().equals(TAG_ITEMS)) {
NodeList nodeList = itemsElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
NamedNodeMap attributes = node.getAttributes();
Node idAtt = attributes.getNamedItem("id");
Node nameAtt = attributes.getNamedItem("name");
System.out.println("id = " + idAtt.getNodeValue());
System.out.println("name = " + nameAtt.getNodeValue());
}
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Which will output...
id = 0
name = a
id = 1
name = b
All of this could be greatly reduced by using XPath, for example, if all the item nodes are the same name, then you could just use
/items/item
As the query. If the node names are different, but the attributes are the same, then you could use
/items/*[#id]
which will list all the nodes under items which has an id attribute, or
/items/*[#name]
which will list all the nodes under items which has an name attribute...
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
try (InputStream is = Test.class.getResourceAsStream("/Test.xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile("/items/item");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
expression = xpath.compile("/items/*[#id]");
nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
expression = xpath.compile("/items/*[#name]");
nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
process(nodes);
} catch (Exception exp) {
exp.printStackTrace();
}
}
protected static void process(NodeList nodes) {
for (int index = 0; index < nodes.getLength(); index++) {
Node item = nodes.item(index);
NamedNodeMap attributes = item.getAttributes();
Node idAtt = attributes.getNamedItem("id");
Node nameAtt = attributes.getNamedItem("name");
System.out.println("id = " + idAtt.getNodeValue() + "; name = " + nameAtt.getNodeValue());
}
}
}
I'm new to Java. I saw many example about reading XML and when I tried to copy to my code I got an error that getTagValue is undefined.
I'm using Eclipse, JRE 1.6.
As well as I understand that method (getTagValue) is exist?
This is the errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
this the code:
import java.io.File;
import java.io.ObjectInputStream.GetField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class WriteXMLFile
{
public static void main(String argv[])
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (TransformerException tfe)
{
tfe.printStackTrace();
}
///// read
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This method needs to be included in your class file somewhere
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
I have a XML file with data that is used in both my C# and Java version of a library.
Ideally I want to embed this XML file in a package in that library.
I only need to access it from within my library, so I was wondering: is that possible?
In Java, you could include the XML file itself in the JAR file. You can then use something like this:
InputStream istream = getClass().getResourceAsStream("/resource/path/to/some.xml");
And parse your InputStream as normal.
The above getResourceAsStream() looks in the current classpath, which would include the contents of any JAR files.
book.xml
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
<person>
<first>kunal</first>
<last>kumar</last>
<age>25</age>
</person>
</book>
create a xml file book.xml
made a jar file book.xml.jar and
palce it in war/web-inf/lib folder of your project..
then it will work..
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
#SuppressWarnings("serial")
public class XMLParser extends HttpServlet {
InputStream istream =getClass().getResourceAsStream("/book.xml");
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
try {
doc = docBuilder.parse (istream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// normalize text representation
doc.getDocumentElement ().normalize ();
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;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());
//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());
//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " +
((Node)textAgeList.item(0)).getNodeValue().trim());
//------
}//end of if clause
}//end of for loop with s var
//System.exit (0);
}//end of main
}