I am working with XML file. And I'm complicated with the reading and writing of these files in Java. If somebody has the code, to read and/or to write a XML, to be able to analyze it and to use it, serious of much help.
Felissa:o
Printable View
I am working with XML file. And I'm complicated with the reading and writing of these files in Java. If somebody has the code, to read and/or to write a XML, to be able to analyze it and to use it, serious of much help.
Felissa:o
Hello, what do you want to do? , if it is to parse xml you can work with DOM or SAX being this much more fast since using DOM to parse this load the document in memory and creates an object from, example of DOM:
Code:<?xml version="1.0"?>
<company>
<employee>
<firstname>Tom</firstname>
<lastname>Cruise</lastname>
</employee>
<employee>
<firstname>Paul</firstname>
<lastname>Enderson</lastname>
</employee>
<employee>
<firstname>George</firstname>
<lastname>Bush</lastname>
</employee>
</company>
if you want to continue investigating there are very interesting things like api of XPATH for java (something like query, so that you do not have to cross xml complete in java)Code:import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String argv []) {
try {
File file = new File("c:\\MyXMLFile.xml" );
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement ().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee") ;
System.out.println("Information of all employees") ;
for (int s = 0 ; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE ) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname" );
Element fstNmElmnt = (Element) fstNmElmntLst.item (0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)) .getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname") ;
Element lstNmElmnt = (Element) lstNmElmntLst.item (0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + (( Node) lstNm.item(0)) .getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Java XPath API
also this JDOM Simplify XML programming with JDOM
and here is the articulate where they speak of how turning from SAX to DOM
Tip: Converting from SAX
Marcus:cool: