wustrive_2008 发表于 2013-1-26 14:02:02

JDOM解析XML

  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"));}
页: [1]
查看完整版本: JDOM解析XML