JDOM解析XML
程序员文章站
2022-05-28 08:02:38
...
//输出xml文档
//1.创建Document
Document doc = new Document();
//2.创建根节点
Element root = new Element( "student-list" );
//3.创建根节点下的子节点并设置属性
Element stu = new Element( "student" );
stu.setAttribute( "id", "0045" );
//4.封装属性
Attribute attr = new Attribute( "title","秀夺" );//Attribute:封装属性
stu.setAttribute( attr );
//创建根节点下的子节点
Element name = new Element( "name" );
name.setText( "jock" );//设置元素内容
//5.add
stu.addContent( name );
root.addContent( stu );
doc.addContent( root );
//6.构造输出流
XMLOutputter xmlOut = new XMLOutputter();
try {
//7.输出为指定的xml文档
xmlOut.output( doc, new FileOutputStream( "stu111.xml" ) );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//1.创建Document
Document doc = new Document();
//2.创建根节点
Element root = new Element( "student-list" );
//3.创建根节点下的子节点并设置属性
Element stu = new Element( "student" );
stu.setAttribute( "id", "0045" );
//4.封装属性
Attribute attr = new Attribute( "title","秀夺" );//Attribute:封装属性
stu.setAttribute( attr );
//创建根节点下的子节点
Element name = new Element( "name" );
name.setText( "jock" );//设置元素内容
//5.add
stu.addContent( name );
root.addContent( stu );
doc.addContent( root );
//6.构造输出流
XMLOutputter xmlOut = new XMLOutputter();
try {
//7.输出为指定的xml文档
xmlOut.output( doc, new FileOutputStream( "stu111.xml" ) );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}