package WildCat.Xml.JDom;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
用Jdom编写xml文档:
1.
public class JdomTest1 {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//获得根节点
Document document=new Document();
//第一级元素
Element root=new Element("学生花名册");
//把元素加入到根节点上
document.addContent(root);
//二级元素
Element student=new Element("学生");
root.addContent(student);
//注释
Comment comment1=new Comment("计算机学院计113——1班");
root.addContent(comment1);
//属性
Attribute num=new Attribute("学号","01");
student.setAttribute(num);
student.addContent(new Element("姓名").setText("WildCat")).addContent(new Element("性别").setText("男"));
//设定输出格式
Format format=Format.getPrettyFormat();
XMLOutputter out=new XMLOutputter(format);
try {
out.output(document, new FileOutputStream("JDOM.xml"));
System.out.println("写入成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
用Jdom解析xml:
package WildCat.Xml.JDom;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.jdom.Attribute;
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 JDomTest2 {
public static void main(String [] args) throws Exception
{
SAXBuilder bulider=new SAXBuilder();
Document doc=bulider.build(new File("JDOM.xml"));
//获得根节点
Element root=doc.getRootElement();
System.out.println(root.getName());
//获得二级元素 学生
Element student=root.getChild("学生");
//获得属性
List num=student.getAttributes();
for(int i=0;i<num.size();i++)
{
Attribute attr=(Attribute)num.get(i);
String attrName=attr.getName();
String attrValue=attr.getValue();
//输出
System.out.println(attrName+"="+attrValue);
}
//获得三级元素 学生
Element name=student.getChild("姓名");
System.out.println(name.getName()+":"+name.getText());
//删除元素
student.removeChild("性别");
//把删除后的文档放到JDOM2.xml中
XMLOutputter out=new XMLOutputter(Format.getPrettyFormat());
out.output(doc, new FileOutputStream("JDOM2.xml"));
}
}
用Jdom编写及解析xml文档
程序员文章站
2022-05-28 08:32:55
...
转载于:https://www.cnblogs.com/lixingle/archive/2012/07/23/3313030.html
下一篇: 苹果联合创始人呼吁苹果开放架构