Below two classes. I have a problem with writing string to file in java. Why in my file xml.txt I get null? Why I can't write String a = px.readXml(url) ? In xml.txt I've only null
package xml;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.StringTokenizer;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class PrintXml {
public String readXml(URL url) throws ParserConfigurationException, MalformedURLException, IOException, SAXException
{
//URL url = new URL("http://www.nbp.pl/kursy/xml/a093z150515.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(url.openStream());
Element root = doc.getDocumentElement();
//System.out.println(root.getTagName());
NodeList children = root.getChildNodes();
int liczbaLinijek = children.getLength();
for(int i = 0; i<children.getLength();i++)
{
Node child = children.item(i);
if (child instanceof Element)
{
Element childElement = (Element)child;
NodeList childrenPozycja = childElement.getChildNodes();
for (int j = 0; j<childrenPozycja.getLength(); j++)
{
Node childPozycja = childrenPozycja.item(j);
if (childPozycja instanceof Element)
{
String nameChf = "CHF";
Double kurs;
Element childPozycjaElement = (Element) childPozycja;
String listaKursow = childPozycjaElement.getTextContent();
//System.out.println(listaKursow);
}
}
}
}
return null;
}
public String writeXml(String toFile) throws IOException
{
PrintWriter out = new PrintWriter(new FileWriter("xml.txt"));
out.println(toFile);
out.close();
return null;
}
}
and here is testing class:
package xml;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.StringTokenizer;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class PrintXmlTester {
public static void main(String[] args) throws MalformedURLException,
ParserConfigurationException, SAXException, IOException {
URL url = new URL("http://www.nbp.pl/kursy/xml/a093z150515.xml");
PrintXml px = new PrintXml();
String a = px.readXml(url);
px.writeXml(a);
}
}
}
To return value of listaKursow you can add return statement in readXml() like below:
public String readXml(URL url) throws ParserConfigurationException, MalformedURLException, IOException, SAXException
{
//...
//Declare listaKursow here
String listaKursow = "";
for(int i = 0; i<children.getLength();i++)
{
//..
for (int j = 0; j<childrenPozycja.getLength(); j++)
{
Node childPozycja = childrenPozycja.item(j);
if (childPozycja instanceof Element)
{
String nameChf = "CHF";
Double kurs;
Element childPozycjaElement = (Element) childPozycja;
String listaKursowTemp = childPozycjaElement.getTextContent();
//System.out.println(listaKursow);
//return value of listaKursow
listaKursow = listaKursow + listaKursowTemp;
}
}
}
return listaKursow;
}
However you should note that this would return first value of listaKursow in Xml.
If you are looking for all values of elements as String, you can add them to a List and return list.toString() or concatenate String variable in each iteration.
EDIT: Based on your inputs I have modified my post to return all lists
#hitz answer is good, but I would suggest using StringBuilder for this. It is far more efficient and nicer to look at.
public String readXml(URL url) throws ParserConfigurationException, MalformedURLException, IOException, SAXException
{
//...
//Declare listaKursow here
final StringBuilder listaKursow = new StringBuilder();
for(int i = 0; i<children.getLength();i++)
{
//..
for (int j = 0; j<childrenPozycja.getLength(); j++)
{
final Node childPozycja = childrenPozycja.item(j);
if (childPozycja instanceof Element)
{
final String nameChf = "CHF";
Double kurs;
final Element childPozycjaElement = (Element) childPozycja;
listaKursow.append( childPozycjaElement.getTextContent() );
}
}
}
return listaKursow.toString();
}
Related
How could I get value based on a key from an XML content http enpoint, so it is something like
<authority.result result="found 7 matches" startToken="xxxxxxx">
<TestEntry keyId="0right0" test="test" valueId="rightValue123" version="1"/>
<TestEntry keyId="0wrong" test="test" valueId="0wrongValue" version="1"/>
<TestEntry keyId="0wrong0" test="test" valueId="wrong" version="1"/>
</authority.result>
I would like to get the valueId when keyId=="0right0" only, I previously wrote following but could not get value for a specific key.
URL url = new URL(endpoint);
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(url.openStream());
String latest;
while (reader.hasNext()) {
if (reader.next() == XMLStreamConstants.START_ELEMENT) {
if (reader.getLocalName().equals("valueId")) {
latest = reader.getElementText();
return latest;
}
}
}
You need to distinguish XML element from an attribute. To read attribute name and value you have to use getAttributeName and getAttributeValue methods respectively.
Below you find example code how to read attributes:
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
public class XmlStreamApp {
public static void main(String[] args) throws IOException, XMLStreamException {
...
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
Optional<String> value = findValueForTestEntry(reader, "0right0");
System.out.println(value);
}
private static Optional<String> findValueForTestEntry(XMLStreamReader reader, String keyValue) throws XMLStreamException {
while (reader.hasNext()) {
if (reader.next() == XMLStreamConstants.START_ELEMENT) {
String localName = reader.getLocalName();
if ("TestEntry".equals(localName)) {
Optional<String> optionalValue = getValueForKey(reader, keyValue);
if (optionalValue.isPresent()) {
return optionalValue;
}
}
}
}
return Optional.empty();
}
private static Optional<String> getValueForKey(XMLStreamReader reader, String keyValue) {
String value = "";
boolean found = false;
for (int attr = reader.getAttributeCount() - 1; attr >= 0; attr--) {
QName attributeName = reader.getAttributeName(attr);
if (attributeName.getLocalPart().equals("keyId")) {
found = keyValue.equals(reader.getAttributeValue(attr));
}
if (attributeName.getLocalPart().equals("valueId")) {
value = reader.getAttributeValue(attr);
}
}
return found ? Optional.of(value) : Optional.empty();
}
}
Above code prints:
Optional[rightValue123]
You could use an xpath to get to the desired value :
string(//TestEntry[#keyId="0right0"]/#valueId)
I'm relatively new to XML processing with Java, so expect some mistakes, but anyway...I'm trying to parse the following XML data:
http://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx
I would like to accomplish this using a function, where the name of the XML tag and NodeList are passed in as parameters, and it returns the content.
Thanks.
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class Files {
#SuppressWarnings("unused")
public static void main (String [] args) throws IOException, ParserConfigurationException, SAXException{
String address = "/home/leo/workspace/Test/Files/src/file.xml";
String author = "author";
String title = "title";
String genre = "genre";
String price = "price";
String publish = "publish_date";
String descr = "description";
File xmlFile = new File(address);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getNodeName());
NodeList n = doc.getElementsByTagName("book");
System.out.println("Number of books " + n.getLength());
getElement(author, n);
}
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
Element showElement = (Element)showNode;
System.out.println(elementName + ": " +
showElement.getAttribute(elementName)
);
}
}
}
The problem is : showElement.getAttribute(elementName)
you want to get the value of a node,but getAttribute is to get the attribute of the node,you should figure out what attribute means in XML.
you can get the value like this:
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
NodeList nl = showNode.getChildNodes();
for(int j=0;j<nl.getLength();j++)
{
Node nd=nl.item(j);
if(nd.getNodeName().equals(elementName))
{
System.out.println(elementName + ":" + nd.getTextContent());
}
}
}
}
}
Looking for someone to look over my simple code. I am rather new to what I am doing and know that I am probably just making a simple mistake somewhere.
I am parsing an xml file that is over http and trying to print out the text associated with the elements to the screen, and make an object that is populated by the text in those elements.
I can get all of the elements and associated text printed but the objects all have a null value in their fields. Let me know if I anything needs to be explained better.
Code is found below:
Object Class:
package com.entities;
public class StageOfLife
{
private String endDate;
private String offerData;
private String offerType;
private String redemption;
private String startDate;
private String termsConditions;
private String title;
private String merchantDescription;
private String merchantLogo;
private String merchantName;
public StageOfLife() {
}
public StageOfLife(String endDate, String offerData, String offerType,
String redemption, String startDate, String termsConditions,
String title, String merchantDescription, String merchantLogo,
String merchantName)
{
// Getters Setters HEre
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(endDate);
buffer.append("\n");
buffer.append(offerData);
buffer.append("\n");
buffer.append(offerType);
buffer.append("\n");
buffer.append(redemption);
buffer.append("\n");
buffer.append(startDate);
buffer.append("\n");
buffer.append(termsConditions);
buffer.append("\n");
buffer.append(title);
buffer.append("\n");
buffer.append(merchantDescription);
buffer.append("\n");
buffer.append(merchantLogo);
buffer.append("\n");
buffer.append(merchantName);
return buffer.toString();
}
}
And here is is the class with the methods and main:
package com.xmlparse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.entities.StageOfLife;
public class XmlParserStage
{
Document dom;
DocumentBuilder db;
List<StageOfLife> myStageList;
public XmlParserStage(){
//create a list to hold the StageOfLife objects
myStageList = new ArrayList<StageOfLife>();
}
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
db = dbf.newDocumentBuilder();
//parse to get DOM representation of the XML file
dom = db.parse("http:/url/goes/here");
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument() {
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("Offer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength(); i++) {
//get the elements
Element solEl = (Element)nl.item(i);
//get the StageOfLife object
StageOfLife sol = getStageOfLife(solEl);
//add it to list
myStageList.add(sol);
}
}
}
/*
take an <offer> element and read the values in, create
an StageOfLife object and return it
*/
private StageOfLife getStageOfLife(Element solEl) {
/*
for each <offer> element get the values
*/
String endDate = getTextValue(solEl,"EndDate");
String offerData = getTextValue(solEl,"OfferData");
String offerType = getTextValue(solEl,"OfferType");
String redemption = getTextValue(solEl,"Redemption");
String startDate = getTextValue(solEl,"StartDate");
String termsConditions = getTextValue(solEl,"TermsConditions");
String title = getTextValue(solEl,"Title");
String merchantDescription = getTextValue(solEl,"MerchantDescription");
String merchantLogo = getTextValue(solEl,"MerchantLogo");
String merchantName = getTextValue(solEl,"MerchantName");
//Create a new StageOfLife object with the value read from the xml nodes
StageOfLife sol = new StageOfLife(endDate, offerData, offerType,
redemption, startDate, termsConditions,
title, merchantDescription, merchantLogo,
merchantName);
return sol;
}
/*
take a xml element and the tag name, look for the tag and get
the text content
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
System.out.print(el + ":" + textVal);
System.out.println();
}
return textVal;
}
/*
Calls getTextValue and returns a int value
*/
private int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele,tagName));
}
private void printData(){
System.out.println("Number of Offers: '" + myStageList.size() + "'.");
Iterator it = myStageList.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
public void run() {
//parse the xml file and get the dom object
parseXmlFile();
//get each stageoflife element and create a StageOfLife object
parseDocument();
//Iterate through the list and print the data
printData();
}
public static void main(String [] args) throws ClientProtocolException, IOException {
XmlParserStage xmlParser = new XmlParserStage();
xmlParser.httpClient();
xmlParser.run();
}
}
your constructor is not doing anything!
public StageOfLife(String endDate, String offerData, String offerType,
String redemption, String startDate, String termsConditions,
String title, String merchantDescription, String merchantLogo,
String merchantName)
{
// set the data
this.endDate = endDate;
...
}
But much better is to use Java XML Binding jaxb. it automatically maps java classes to xml
Take a look at Jaxb library. It can do all the heavy lifting for you.
JAXB Homepage
Vogella Tutorial
Mkyong Tutorial
Set the values you are passing to the StageOfLife constructor to the variables.
Try this
public class Tester {
String getString() throws IOException, ParserConfigurationException, SAXException {
InputStream inputStream = //your stream from http
String sa = "";
int cc;
while((cc = inputStream.read()) != -1) {
sa += (char) cc;
}
ByteArrayInputStream sr = new ByteArrayInputStream(sa.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(sr);
Node node=doc.getDocumentElement().getFirstChild();
String data=node.getNodeName();
return data;
}
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
Tester t = new Tester();
System.out.println(t.getString());
}
Im new in Java, and i have a task to Parse one xml file using http with current url http://belbooner.site40.net/testXmls/details.xml
I created Some class to parse it using Dom method, but im having java.lang.NullPointerException while trying to get one Nodes value
So here's the code
import java.security.KeyStore.Builder;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.swing.text.Document;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.*;
import org.w3c.dom.CharacterData;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class RequestResponse {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
RequestResponse req= new RequestResponse();
req.getHTTPXml(url);
}
void getHTTPXml(URL url) throws ParserConfigurationException, IOException, SAXException {
//URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ACCEPT","application/xml");
InputStream xml = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(xml);
System.out.println(document);
String doctype = conn.getContentType();
System.out.print(doctype);
NodeList root = document.getChildNodes();
Node server = getNodes("server",root);
Node check = getNodes("check", server.getChildNodes());
NodeList nodes = check.getChildNodes();
String checkid= getNodeValue("checkid", nodes);
System.out.println(checkid);
conn.disconnect();
//return (Document) DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml);
}
Node getNodes(String tagName, NodeList nodes) {
for(int i=0; i< nodes.getLength();i++) {
Node node= nodes.item(i);
if(node.getNodeName().equalsIgnoreCase(tagName)) {
return node;
}
}
return null;
}
String getNodeValue(String tagName, NodeList nodes ) {
for ( int i = 0; i < nodes.getLength(); i++ ) {
Node node = nodes.item(i);
if (node.getNodeName().equalsIgnoreCase(tagName)) {
NodeList childNodes = node.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++ ) {
Node data = childNodes.item(y);
if ( data.getNodeType() == Node.TEXT_NODE ) {
return data.getNodeValue();
}
if(data instanceof CharacterData) {
CharacterData cd= (CharacterData) data;
return cd.getData();
}
}
}
}
return "";
}
}
The stacktrace I'm getting is the following:
application/xmlException in thread "main" java.lang.NullPointerException at
RequestResponse.getHTTPXml(RequestResponse.java:45) at
RequestResponse.main(RequestResponse.java:22)
After changin Node server = getNodes("server",root); to `
Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());`
`application/xmlException in thread "main" java.lang.NullPointerException
at RequestResponse.getHTTPXml(RequestResponse.java:49)
at RequestResponse.main(RequestResponse.java:22)
`
Please help me to find the issue.
The problem is that Node server = getNodes("server",root); is returning null.
Why does this happen? Well look how you implemented getNodes
Node getNodes(String tagName, NodeList nodes) {
for(int i=0; i< nodes.getLength();i++) {
Node node= nodes.item(i);
if(node.getNodeName().equalsIgnoreCase(tagName)) {
return node;
}
}
return null;
}
You are giving as input the document root which is a single "Result" node, you iterate through it and you compare if the node's name is in this case "server" which never will be, hence you return null and get a NPE.
Your node look up must be done in the following way:
NodeList root = document.getChildNodes();
// Keep in mind that you have the following structure:
// result
// server
// checks
// check
// checkId
// check
// checkId
Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());
Node checks = getNodes("checks", server.getChildNodes());
NodeList childNodes = checks.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node possibleCheck = childNodes.item(i);
if (possibleCheck.getNodeName().equals("check")) {
String checkid = getNodeValue("checkid", possibleCheck.getChildNodes());
System.out.println(checkid);
}
}
This way you'll be iterating through the correct node list.
Using XPath is more efficient and flexible (than normal iteration) while parsing xml.
XPath Tutorial from IBM
XPath Reference Orielly tutorial
Xpath Reference Oracle java tutorial
Try below code.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class RequestResponse {
public static void main(String[] args) throws ParserConfigurationException,
IOException, SAXException {
URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
RequestResponse req = new RequestResponse();
req.getHTTPXml(url);
}
void getHTTPXml(URL url) throws ParserConfigurationException, IOException,
SAXException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ACCEPT", "application/xml");
InputStream xml = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(xml);
System.out.println(document);
String doctype = conn.getContentType();
System.out.println(doctype);
XPathFactory pathFactory = XPathFactory.newInstance();
XPath path = pathFactory.newXPath();
XPathExpression expression;
try {
expression = path.compile("/result/server/checks/check/checkid");
NodeList nodeList = (NodeList) expression.evaluate(document,
XPathConstants.NODESET);
String checkids[] = getNodeValue(nodeList);
for (String checkid : checkids) {
System.out.print(checkid + ", ");
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
conn.disconnect();
}
String[] getNodeValue(NodeList nodes) {
String checkIds[] = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
checkIds[i] = node.getTextContent();
}
return checkIds;
}
}
im trying to get all element of an XML file and put it into a ArrayList>> with a recursive method, but i get an error : Exception in thread "main" java.lang.StackOverflowError at java.util.ArrayList.
the error is getting when i make a recursive call : GetAllXml(ListTree);
and i want to get a strcuture like this [[[un]] , [[deux,trois,quatre]] , [[cinq,six,sept],[huit,noeuf],[dix,onze]]]
here is my code:
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class esperant {
/**
* #param args
*/
private static List<Element> getChildren(Node parent)
{
NodeList nl = parent.getChildNodes();
List<Element> children = new ArrayList<Element>(nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element)
children.add((Element) n);
}
return children;
}
public static void GetAllXml(ArrayList<ArrayList<ArrayList<Element>>> ListTree)
{
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
int level = ListTree.size()-1;
for (int i=0;i<ListTree.get(level).size();i++)
{
for (int j=0;j<ListTree.get(level).get(i).size();j++)
{
ArrayList<Element> childOfChild = new ArrayList<Element>();
childOfChild.addAll(getChildren(ListTree.get(level).get(i).get(j)));
child.add(childOfChild);
}
}
ListTree.add(child);
GetAllXml(ListTree);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ArrayList<ArrayList<Element>>> ListTree = new ArrayList<ArrayList<ArrayList<Element>>>();
ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
ArrayList<Element> childOfChild = new ArrayList<Element>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("test.xml");
Element root = doc.getDocumentElement();
childOfChild.add(root);
child.add(childOfChild);
ListTree.add(child);
GetAllXml(ListTree);
System.out.println(ListTree);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is the xml file :
<?xml version="1.0" encoding="iso-8859-1"?>
<un>
<deux> <cinq></cinq> <six></six> <sept></sept> </deux>
<trois> <huit></huit><noeuf></noeuf> </trois>
<quatre><dix></dix><onze></onze> </quatre>
</un>
Change Your GetAllXml(X) like this, it would work. As Every one above said , there is no way out from this method.
final ArrayList<ArrayList<Element>> child = new ArrayList<ArrayList<Element>>();
final int level = ListTree.size() - 1;
for (int i = 0; i < ListTree.get(level).size(); i++)
{
for (int j = 0; j < ListTree.get(level).get(i).size(); j++)
{
final ArrayList<Element> childOfChild = new ArrayList<Element>();
childOfChild.addAll(getChildren(ListTree.get(level).get(i).get(j)));
if (childOfChild.size() > 0)
{
child.add(childOfChild);
}
}
}
if (child.size() > 0)
{
ListTree.add(child);
GetAllXml(ListTree);
}
Every call on GetAllXml(X), whatever else it does, ends up calling GetAllXml(X) passing the same value as its argument. So it's obvious that it will recurse infinitely.