六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 31|回复: 0

JDOM解析XML

[复制链接]

升级  42%

29

主题

29

主题

29

主题

秀才

Rank: 2

积分
113
 楼主| 发表于 2013-1-26 14:02:02 | 显示全部楼层 |阅读模式
  JDOM生成XML文档:(文档的输出)
public static void main(String[] args) throws IOException, IOException {Document document = new Document();Element root = new Element("root");document.addContent(root);//添加注释Comment comment =new Comment("this is my comments");root.addContent(comment);Element e = new Element("hello");e.setAttribute("wubaoguo","wustrive_2008");root.addContent(e);Attribute attr = new Attribute("test","world");Element e2 = new Element("world");e2.setAttribute(attr);root.addContent(e2);e2.addContent(new Element("xxx").setAttribute("a","b").setAttribute("c","d").setText("content"));//设置输出格式Format format = Format.getPrettyFormat();format.setIndent("    ");XMLOutputter out = new XMLOutputter(format);out.output(document,new FileOutputStream("jdom.xml"));}JDOM解析XML(文档的输入)public static void main(String[] args) throws JDOMException, IOException {SAXBuilder builder = new SAXBuilder();Document doc = builder.build(new File("jdom.xml"));Element element = doc.getRootElement();System.out.println(element.getName());Element hello = element.getChild("hello");System.out.println(hello.getText());List list = hello.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);}hello.removeChild("welcome");XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));out.output(doc, new FileOutputStream("jdom2.xml"));}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表