ITPub博客

首页 > 应用开发 > Java > JDom新建和读取xml

JDom新建和读取xml

原创 Java 作者:gxbgxb 时间:2007-02-13 14:14:10 0 删除 编辑

//package xml;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;

//import org.jdom.*;
import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;


public class test {

private static String titlename;

private String chapter;

private String topic;

public static void main(String [] msg){
wriXml();
// try{
readXml();
// }catch (Exception e){e.printStackTrace();}
}
public static void readXml() {
SAXBuilder builder=new SAXBuilder();
try{
Document document=builder.build(new File("contents.xml"));
Element root=document.getRootElement();
Element title=root.getChild("title");
System.out.println(title.getText());

Element contents=root.getChild("contents");
List lis=contents.getChildren("chapter");
Iterator it=lis.iterator();
while(it.hasNext()){
Element chapter=(Element) it.next();
System.out.println(chapter.getAttribute("title"));
}
}catch(Exception e){e.printStackTrace();}


}

public static void wriXml(){

Element ele=new Element("boot");
Document doc=new Document(ele);

ele.addAttribute(new Attribute("vin","123456789"));
ele.addContent(new Element("first").addContent("guoxb"));
ele.addContent(new Element("second").addContent("30"));
ele.addContent(new Element("third").addContent("univercity"));
ele.addContent(new Element("first").addContent("girlfri").addAttribute("name","22"));
ele.addContent(new Element("right"));
ele.addContent(new Comment("这是一条主释"));
Element gg=ele.getChild("right");
gg.addContent(new Element("pkg").addContent("thhhhhhhh"));

//访问子元素
Element fir=ele.getChild("first");
//去处子元素
boolean remo=ele.removeChild("first");

//打印输出xml
try{
XMLOutputter out=new XMLOutputter(" ",true);
out.setEncoding("gb2312");
out.output(doc,System.out);



//保存到xml文档中
FileWriter fi=new FileWriter("./gxb.xml");
out.output(doc,fi);
fi.close(); }catch (Exception e){e.printStackTrace();}
}
}

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/790981/viewspace-899430/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 利用Jdom读取xml
请登录后发表评论 登录
全部评论
  • 博文量
    20
  • 访问量
    340603