dom4j生成和解析xml文件

packagecom.test;

importjava.io.File;

importjava.io.PrintWriter;

importjava.util.Iterator;

importorg.dom4j.Document;

importorg.dom4j.DocumentException;

importorg.dom4j.DocumentHelper;

importorg.dom4j.Element;

importorg.dom4j.io.SAXReader;

importorg.dom4j.io.XMLWriter;

/**

*@说明DOM4J解析XML

*@authorcuisuqiang

*@version1.0

*@since

*/

@SuppressWarnings("unchecked")

publicclassDom4jDemo{

publicstaticvoidmain(String[]args){

Stringfile="C:\\p.xml";//文件存放位置

Dom4jDemodj=newDom4jDemo();

dj.createXml(file);

dj.parserXml(file);

}

/**

*生成XML

*@paramfilePath文件路径

*/

publicvoidcreateXml(StringfilePath){

Documentdocument=DocumentHelper.createDocument();

Elementemployees=document.addElement("persons");

Elementemployee=employees.addElement("person");

Elementname=employee.addElement("name");

name.setText("java小强");

Elementsex=employee.addElement("sex");

sex.setText("男");

Elementage=employee.addElement("age");

age.setText("26");

try{

//PrintWriter带有编码格式的构造方法有助于解决乱码问题

PrintWriterpw=newPrintWriter(filePath,"utf-8");

XMLWriterxmlWriter=newXMLWriter(pw);

xmlWriter.write(document);

xmlWriter.close();

}catch(Exceptione){

e.printStackTrace();

}

}

/**

*解析XML

*@paramfilePath文件路径

*/

publicvoidparserXml(StringfilePath){

FileinputXml=newFile(filePath);

SAXReadersaxReader=newSAXReader();

try{

Documentdocument=saxReader.read(inputXml);

Elementroot=document.getRootElement();

for(Iteratorpersons=root.elementIterator();persons.hasNext();){

Elementperson=(Element)persons.next();

for(Iteratorpro=person.elementIterator();pro.hasNext();){

Elementnode=(Element)pro.next();

System.out.print(node.getName()+":"+node.getText()+"\t");

}

System.out.println();

}

}catch(DocumentExceptione){

e.printStackTrace();

}

}

}

相关推荐