Java read-write XML file

Source: Internet
Author: User

The XML file to read

<?xml version= "1.0" encoding= "GB2312"?>
< student roster >
< student sex = "male" >
< name > Li Hua </name >
< age >14</Age >
</Students >
< student sex = "male" >
< name > Zhang San </name >
< age >16</Age >
</Students >
</Student Roster >

Package XML;

Import Java.io.FileOutputStream;
Import Java.io.OutputStreamWriter;
Import Java.io.Writer;
Import Java.util.Iterator;
Import Java.util.Vector;

Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.transform.OutputKeys;
Import Javax.xml.transform.Result;
Import Javax.xml.transform.Source;
Import Javax.xml.transform.Transformer;
Import javax.xml.transform.TransformerConfigurationException;
Import javax.xml.transform.TransformerException;
Import Javax.xml.transform.TransformerFactory;
Import Javax.xml.transform.dom.DOMSource;
Import Javax.xml.transform.stream.StreamResult;

Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList;
Import Org.w3c.dom.Text;

public class Domtest {
Vector Students_vector;

Private Vector readxmlfile (String file) throws Exception {
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
Documentbuilder builder = Dbf.newdocumentbuilder ();
Document doc = builder.parse (file); Get to XML file

Start reading below
Element root = Doc.getdocumentelement (); Get root element
NodeList students = root.getelementsbytagname_r ("student");
Students_vector = new Vector ();
for (int i = 0; i < students.getlength (); i++) {
Get every student element at a time
element ss = (Element) students.item (i);

Create an instance of a student
Student stu = new Student ();
Stu.setsex (Ss.getattribute ("gender"));

NodeList names = Ss.getelementsbytagname_r ("name");
Element e = (element) names.item (0);
Node t = e.getfirstchild ();
Stu.setname (T.getnodevalue ());

NodeList ages = Ss.getelementsbytagname_r ("Age");
E = (Element) ages.item (0);
t = E.getfirstchild ();
Stu.setage (Integer.parseint (T.getnodevalue ()));

Students_vector.add (Stu);
}
return students_vector;
}

Write XML file
public static void Callwritexmlfile (Document doc, Writer W, String encoding) {
try {
SOURCE Source = new Domsource (DOC);

result = new Streamresult (w);

Transformer Xformer = Transformerfactory.newinstance ()
. Newtransformer ();
Xformer.setoutputproperty (outputkeys.encoding, ENCODING);
Xformer.transform (source, result);

} catch (Transformerconfigurationexception e) {
E.printstacktrace ();
} catch (Transformerexception e) {
E.printstacktrace ();
}
}

private void Writexmlfile (String outfile) {
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
Documentbuilder builder = null;
try {
Builder = Dbf.newdocumentbuilder ();
} catch (Exception e) {
}
Document doc = Builder.newdocument ();

Element root = doc.createelement ("Student roster");
Doc.appendchild (root); To add a root element to a document

Get Student Information
for (int i = 0; i < students_vector.size (); i++) {
Student s = (student) students_vector.get (i);
Create a student
Element stu = doc.createelement ("student");
Stu.setattribute ("Gender", S.getsex ());
Root.appendchild (stu);//Add Property

Create a text name node
Element name = doc.createelement ("name");
Stu.appendchild (name);
Text tname = Doc.createtextnode (S.getname ());
Name.appendchild (Tname);

Create text Age Node
Element ages = doc.createelement ("Age");
Stu.appendchild (age); Add age to student nodes
Text Tage = Doc.createtextnode (string.valueof (S.getage ()));
Age.appendchild (Tage); Place the text node on the age node
}
try {
FileOutputStream fos = new FileOutputStream (outfile);
OutputStreamWriter outwriter = new OutputStreamWriter (FOS);
((XmlDocument) doc). Write (Outwriter); Error!
Callwritexmlfile (Doc, Outwriter, "gb2312");
Outwriter.close ();
Fos.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}

public static void Main (String args[]) {
String str = "Xml/student.xml";
Domtest t = new domtest ();
try {
Vector v = t.readxmlfile (str);
Iterator it = V.iterator ();
while (It.hasnext ()) {
Student s = (student) it.next ();
System.out.println (S.getname () + "\ T" + s.getage () + "\ T"
+ S.getsex ());
}
} catch (Exception e) {
E.printstacktrace ();

}

String outfile = "Xml/stucopy.xml";
T.writexmlfile (outfile);

}
}


Class student{
Private String sex;
private String name;
private int age;

public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
public void Setsex (String s) {sex=s;}
Public String Getsex () {return sex;}

public void SetName (String n) {name=n;}
Public String GetName () {return name;}
}

Java read-write XML file

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.