Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Type your question here I need sample code to read any XML file in java. The pro

ID: 3537915 • Letter: T

Question

Type your question here

I need sample code to read any XML file in java. The program should summarize number of elements with their child element (name, attribute, value)

This should be read any xml file without defining/knowing any nodes or elements in the actual code.

for example, for below sample xml file,

it should get "root element is Testcases, there are two tests, first test is fail and second is pass.

I can parse any XML file and get the nodes in the object list having parent node and its child nodes both with element name, atributes and values.

Please help.

Explanation / Answer


up vote

-7

down vote

favorite

I need sample code to read any XML file in java. The program should summarize number of elements with their child element (name, attribute, value)


This should be read any xml file without defining/knowing any nodes or elements in the actual code.


for example, for below sample xml file,


<Testcases>

<test>

<id ="123">

<result="pass">

<test>

<test>

<id ="345">

<result="fail">

<test>

<Testcases>

it should get "root element is Testcases, there are two tests, first test is fail and second is pass.


I can parse any XML file and get the nodes in the object list having parent node and its child nodes both with element name, atributes and values.



1

down vote

given that doesnt seem to be a valid xml, a procedure to read and xml file in java is the following


public static void main(String argv[]) {


try {


File myfile = new File(pathtofile.xml);

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.parse(myfile);

doc.getDocumentElement().normalize();


System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("test");

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("id", eElement));

System.out.println("Last Name : " + getTagValue("result", eElement));



}

}

} catch (Exception e) {

e.printStackTrace();

}

}


private static String getTagValue(String sTag, Element eElement) {


NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();


Node nValue = (Node) nlList.item(0);


return nValue.getNodeValue();