Java and XML (ii) write XML reading and writing programs in Java
Source: Internet
Author: User
Xml| program Java and XML (ii) write XML reading and writing programs in Java
This is to read the XML file Java program, I debug good. The DOM method is used to read the XML file into the vector.
Package src;
Import java.io.*;
Import Java.util.Vector;
Import javax.xml.parsers.*;
Import org.w3c.dom.*;
public class ReadXml {
static document document;
private Boolean validating;
Public ReadXml () {
}
Public Vector toread (String filename) {
Vector title=new vector ();
Vector content=new vector ();
String Mystr=new string ();
try {
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Factory.setvalidating (validating);
Documentbuilder builder = Factory.newdocumentbuilder ();
Document = Builder.parse (new File (filename));
Document.getdocumentelement (). normalize ();
Node node = Document.getfirstchild ();
NodeList list = Node.getchildnodes ();
for (int i = 0; i < list.getlength (); i++) {
Node nodeitm = List.item (i);
if (Nodeitm.getnodename (). Equals ("Title")) {
Mystr=nodeitm.getfirstchild (). Getnodevalue ();
Title.addelement (MYSTR);//getfirstchild ()
}
if (Nodeitm.getnodename (). Equals ("Content")) {
Mystr=nodeitm.getfirstchild (). Getnodevalue ();
Content.addelement (MYSTR);
}
}
catch (Exception exp) {
Exp.printstacktrace ();
return null;
}
Vector all=new vector ();
All.add (title);
All.add (content);
return all;
}
public static void Main (string[] args) {
Vector A;
ReadXml my = new ReadXml ();
A = My.toread ("F:\\tomcat5\\webapps\\myxml\\xmldata\\9.xml");
for (int i = 0; i < a.size (); i++) {
System.out.println (A.elementat (i));
}
}
}
This is to write the XML to the file. Among them, Transformer.setoutputproperty (outputkeys.encoding, "GB2312") is related to the coding problem, very important.
Import org.w3c.dom.*;
Import javax.xml.parsers.*;
Import javax.xml.transform.*;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;
Import java.io.*;
public class WriteXml {
Private document document;
private String filename;
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.