///1, generating XML
@Test
public void Createapplicationconfigxml () {
Create Document Object
try {
Document document = Documenthelper.createdocument ();
Element root = document.addelement ("root");//Add Document root
Root.addcomment ("This one comment");//Add a line of comments
Element request = root.addelement ("request"); Add a child node of root
Request.addattribute ("type", "cat");
Request.addattribute ("Flow", "Tong");
Request.addattribute ("Time", "2009");
Element Pro = Request.addelement ("Pro");
Pro.addattribute ("type", "att");
Pro.addattribute ("name", "attachment");
Pro.addtext ("Test ha Son");
Element cd = request.addelement ("Pro");
Cd.addattribute ("type", "CD");
Cd.addattribute ("Name", "special character filter");
Cd.addcdata ("special characters");
Output all raw data, displayed in the compiler
OutputFormat format = Outputformat.createprettyprint ();
Format.setencoding ("UTF-8");//Set the encoding as needed
XMLWriter writer = new XMLWriter (system.out, format);
Document.normalize ();
Writer.write (document);
Writer.close ();
Output all the raw data and use it to generate the new XML file we need
XMLWriter writer2 = new XMLWriter (new FileWriter (New File ("D://test.xml")), format);
Writer2.write (document); Output to File
Writer2.close ();
} catch (Unsupportedencodingexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
Parsing xml
@Test
public void Parseapplicationconfigxml () {
try {
Saxreader sax = new Saxreader ();
Document xmldoc = Sax.read (New File ("D://test.xml"));
Element root = Xmldoc.getrootelement ();//root node
Iterator it = root.elementiterator ("request");
while (It.hasnext ()) {
Element request = (Element) It.next ();
System.out.println (Request.getname ());
System.out.println (Request.attributevalue ("type"));
System.out.println (Request.attributevalue ("Flow"));
System.out.println (Request.attributevalue ("Time"));
}
System.out.println ("-------------------------------------------");
List List = Root.selectnodes ("//pro");
for (int i = 0; i < list.size (); i++) {
Element Pro = (Element) list.get (i);
System.out.println (Pro.getname ());
System.out.println (Pro.attributevalue ("type"));
System.out.println (Pro.attributevalue ("name"));
System.out.println (Pro.gettext ());
System.out.println ("+++++++++++++++++++++++++++++++++");
}
} catch (Documentexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
Java generates XML