dom4j创建、解析XML jar包提供下载

dom4j创建XML:

//用dom4j生成xml文件
Document document = DocumentHelper.createDocument();
Element newspaperElement = document.addElement("NewspaperSync.REQ");
newspaperElement.addComment("this is a newspaper xml");
newspaperElement.addProcessingInstruction("MsgHeader", "text");
Element msgHeaderElement = newspaperElement.addElement("MsgHeader");
Element transactionIDElement = msgHeaderElement.addElement("TransactionID");
for(int i=1;i<5;i++){
Element id = transactionIDElement.addElement("ID");
id.setText("i"+i);
}
Element timestampElement = msgHeaderElement.addElement("Timestamp");
Element viasElement = msgHeaderElement.addElement("Vias");
Element viaElement = viasElement.addElement("Via");
viaElement.setText("100.2000.12345");
Element viabakElement = viasElement.addElement("Via");
viabakElement.setText("200.3000.56789");
try{
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter output = new XMLWriter(new FileWriter(new File(sendESGxml+"1111.xml")), format); //sendESGxml是路径
output.write(document);
output.close();
}catch(IOException e){
System.out.println(e.getMessage());
}






dom4j解析XML,并修改其中内容:
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("f:/xml/1111.xml"));
List list = document.selectNodes("//MsgHeader/TransactionID");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Element element = (Element) iterator.next();
Iterator iter = element.elementIterator("ID");
while(iter.hasNext()){
Element idElement = (Element)iter.next();
if(idElement.getText().equals("i2")){
idElement.setText("island");
}
}
}
XMLWriter output = new XMLWriter(new FileWriter(new File("c:/22.xml")));
output.write(document);
output.close();
}



其中用到了2个包:分别是dom4j-1.6.1.jar和jaxen.jar

[color=red]注:在创建xml时只需要dom4j包就可以了,而在解析修改xml的时候必须有jaxen包才行,否则会报错。


错误描述:Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenException
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.elecpaper.buss.action.dom4jUpdate.main(dom4jUpdate.java:24)
[/color]

你可能感兴趣的:(Java)