There are two ways to parse XML files, one is to use DOM to parse, this way to write code more trouble, for the first programmers are more prone to problems; the second is to use the DOM4J package to parse
When you want to use the DOM4J package, you must first introduce the package
Copy Code code as follows:
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.Writer;
Import Java.util.Iterator;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;
Import Org.dom4j.io.XMLWriter;
/**
* @author Icer
*/
public class dom4jdemo{
/**
*
* XML filename generated by @param filename
* @param txtname included in the reconciliation file txt filename
*/
public void Createxml (String filename,string txtname) {
Document document = Documenthelper.createdocument ();
Element root = document.addelement ("root");
Element head = root.addelement ("Head");
Element type = Head.addattribute ("type", "0");
Element code = head.addattribute ("code", "3003");
Element YHLB = head.addelement ("YHLB");
Yhlb.settext ("01");
Element username = head.addelement ("username");
Username.settext ("Gsyh");
Element Password = head.addelement ("password");
Password.settext ("Zheshimima");
Element BODY = root.addelement ("Body");
Element data = body.addelement ("Data");
Element DZWJM = data.addelement ("DZWJM");
Dzwjm.settext (txtname);
try {
Write to File
Writer fileWriter = new FileWriter (fileName);
OutputFormat format = Outputformat.createprettyprint ();
XMLWriter XMLWriter = new XMLWriter (Filewriter,format);
Xmlwriter.write (document);
Xmlwriter.close ();
catch (IOException e) {
System.out.println (E.getmessage ());
}
}
/**
*
* @param filename To resolve file name
* @return Parse XML file with the file name you want to reconcile
*/
public string Parserxml (string FileName) {
String findfilename = ";
File Inputxml = new file (fileName);
Saxreader saxreader = new Saxreader ();
try {
Document document = Saxreader.read (inputxml);
Element root = Document.getrootelement ();
for (Iterator i = Root.elementiterator (), I.hasnext ();) {
Element head = (Element) i.next ();
for (Iterator J = head.elementiterator (); J.hasnext ();) {
Element elem = (Element) j.next ();
System.out.println (Elem.getname () + ":" +elem.gettext ());
for (iterator K=elem.elementiterator (); K.hasnext ();) {
element is last = (Element) k.next ();
System.out.println (Last.getname () + ":" +last.gettext ());
FindFileName = Last.gettext ();
}
}
}
catch (Documentexception e) {
System.out.println (E.getmessage () + "Hello");
}
System.out.println ("dom4j parserxml");
return findfilename;
}
/**
* Test Main method
* @param args
*/
public static void Main (string[] args) {
Dom4jdemo demo = new Dom4jdemo ();
Demo.createxml ("D://request.xml", "test.txt");
Demo.parserxml ("E://request.xml");
}