Java Course

"Source: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

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;
import java.io.FileWriter;
//import java.io.PrintWriter;

public class ReadXMLFile {
static String a;
static String b;
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:\\Programy\\data-set.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("record");
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;

a = eElement.getElementsByTagName("data").item(0).getTextContent();
b = eElement.getElementsByTagName("wartość").item(0).getTextContent();

//System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("date : " + a);//eElement.getElementsByTagName("date").item(0).getTextContent()); System.out.println("value : " + b);// eElement.getElementsByTagName("value").item(0).getTextContent())
//System.out.println("Nick Name : " + Element.getElementsByTagName("nickname").item(0).getTextContent());
//System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

FileWriter out = new FileWriter ("C:\\Programy\\filename.txt",true);
out.write(a + " " + b);
out.write("\r\n");
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}



Dodaj komentarz






Dodaj

© 2013-2024 PRV.pl
Strona została stworzona kreatorem stron w serwisie PRV.pl