package cn.sunjiachao.javabook.jdom; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class XMLMain { public void write() { Element root = new Element("people");//jdom以元素为一个节点的单位 Document document = new Document(root); Element male = new Element("male");//子元素 male.setAttribute("id", "1");//属性 male.addContent(new Element("name").setText("tom"));//叶子节点 male.addContent(new Element("age").setText("24")); document.getRootElement().addContent(male);//加入根元素 XMLOutputter output = new XMLOutputter();//输出 output.setFormat(Format.getPrettyFormat()); File xmlFile = new File("data2.xml"); try { output.output(document, new FileWriter(xmlFile)); } catch (IOException e) { e.printStackTrace(); } } public void read() { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File("data.xml"); try { Document document = builder.build(xmlFile);// 获取文档对象 Element root = document.getRootElement();// 获取根元素 List<Element> children = root.getChildren();// 获取子元素集合,同一层级 for (Element ele : children) { // ... } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { XMLMain main = new XMLMain(); main.read(); main.write(); } }
最近下载更多
最近浏览更多
1443251642 LV1
2022年12月19日
15939671505
2020年12月18日
暂无贡献等级
1234567891011 LV5
2020年6月26日
hfk2020 LV2
2020年5月22日
ujsxyl LV2
2019年8月7日
ph9enix LV4
2019年3月20日
07311514 LV9
2019年2月22日
xueji123456789 LV8
2018年5月31日
1006724407 LV15
2018年4月22日
头晕脑壳疼 LV6
2018年2月1日