JDOM解析XML
程序员文章站
2022-05-28 08:33:37
...
1.导入jdom包
2.JdomParse.java
2.JdomParse.java
package com.lijun.xml.jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class JdomParse {
public static void main(String[] args) throws Exception {
String fileName="output.xml";
//生成XML
createXML(fileName);
//解析XML
parserXML(fileName);
}
/**
* 创建XML
* @param fileName XML文件名
* @throws Exception
*/
private static void createXML(String fileName) throws Exception {
//生成文档根节点
Document document=new Document();
//文档根元素
Element root=new Element("root");
//增加根元素到根节点
document.addContent(root);
//生成元素e1
Element e1=new Element("e1");
//在元素e1上增加注释
e1.addContent(new Comment("this is commnet"));
//在元素e1上增加子元素和子元素属性
Attribute attr1=new Attribute("a2","2");
e1.addContent(new Element("e11").setAttribute("a1","1").setAttribute(attr1));
//将e1元素加载到根元素
root.addContent(e1);
//自定义格式化输出
Format format=Format.getPrettyFormat();
XMLOutputter out=new XMLOutputter(format);
out.output(document,new FileOutputStream(fileName));
}
/**
* 解析XML
* @param fileName 文件名
* @throws Exception
* @throws
*/
private static void parserXML(String fileName) throws Exception{
//创建JDOM解析器
SAXBuilder builder=new SAXBuilder();
//获得根节点
Document doc=builder.build(new File(fileName));
//获得根元素
Element root=doc.getRootElement();
System.out.println(root.getName());
Element e11=root.getChild("e1").getChild("e11");
System.out.println(e11.getText());
List list=e11.getAttributes();
for(int i=0;i<list.size();i++){
Attribute attr=(Attribute)list.get(i);
String attrName=attr.getName();
String attrValue=attr.getValue();
System.out.println(attrName+"="+attrValue);
}
root.removeChild("e1");
//输出到新文件
XMLOutputter output=new XMLOutputter();
output.output(doc,new FileOutputStream("output2.xml"));
//或用如下方法
output.output(doc,new FileWriter("output3.xml"));
}
}
下一篇: 使用JDOM解析XML