JDOM解析以及将对象写入到XML中去

 
 
public class JDOMParseXML {
//解析XML
	public static void main(String[] args) {
		
		SAXBuilder builder = new SAXBuilder();
		
		    //解析文件,指定文件位置;
			Document document = builder.build("person.xml");
			
			//获得根节点
			Element root = document.getRootElement();
			//将获取到的根节点放入到集合中去
			List<Element> list = root.getChildren();
			for(Element e:list){
				System.out.println("name="+e.getChildText("name"));
				System.out.println("sex="+e.getChildText("sex"));
				System.out.println("email="+e.getChildText("email"));
				System.out.println("--------------------------------");
=======================================================================
//对象写入XML文件
public class JDOMWriteXML {
	public static void writeXML(List<Person> persons) {
		//创建根节点
		Element root = new Element("ps");
		//创建Document对象,把根节点加入到Document中
		Document document = new Document(root);
		
		for(Person p:persons){
			//创建p节点
			Element e = new Element("p");
			//给节点添加属性
			e.setAttribute("id",1+"");
			//添加子节点并赋值
			e.addContent(new Element("name").setText(p.getName()));
			e.addContent(new Element("sex").setText(p.getSex()));
			e.addContent(new Element("email").setText(p.getEmail()));
			
			//追加到根节点
			root.addContent(e);
		}
		XMLOutputter out = new XMLOutputter();
		try {
			out.output(document, new FileOutputStream("myperson.xml"));
	

	public static void main(String[] args) {
		List<Person> persons = new ArrayList<>();
		persons.add(new Person("jack", "男", "[email protected]"));
		persons.add(new Person("marry", "女", "[email protected]"));
		persons.add(new Person("john", "男", "[email protected]"));
		persons.add(new Person("kity", "女", "[email protected]"));
		writeXML(persons);


猜你喜欢

转载自blog.csdn.net/lzpzwy/article/details/79574962