欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Jdom生成xml文件

程序员文章站 2022-03-03 15:54:36
...
public static void updateXML(String filePath) throws Exception {
		SAXBuilder sb = new SAXBuilder();
		Document doc = sb.build(new FileInputStream(filePath));//读入文件
		Element root = doc.getRootElement(); //获得根元素
//		Element e = root.getChild("occupation");
//		System.out.println(e.getText());
//		System.out.println(e.getName());
//		System.out.println(e.getAttributeValue("dynasty"));//获取元素属性值
		
//		e.setText("大皇帝");
		
		List li = root.getContent();//所有内容:子元素、注释、文本等
		List list = root.getChildren(); //只有标记内容
		System.out.println(li.size());
		System.out.println(list.size());
		
		Element ele = (Element) list.get(0);
		System.out.println(ele.getText());
		//将doc写入到某一个xml文件中,从而更新硬盘中的文件
//		XMLOutputter xmlOut = new XMLOutputter();
//		xmlOut.output(doc, new FileOutputStream(filePath));
	}



//需要导入jdom.jar包
public static void createXML() throws Exception {
		Element root = new Element("resume");
		Element name = new Element("name");
		Element preName = new Element("preName");
		Element occupation = new Element("occupation");
		Element preOccupation = new Element("preOccupation");
		
		Attribute attr = new Attribute("dynasty", "唐朝");
		occupation.setAttribute(attr);
		
		name.setText("李世明");
		preName.addContent("秦王");
		preOccupation.addContent("将军");
		occupation.addContent("皇帝");
		
		root.addContent(name);
		root.addContent(preName);
		root.addContent(occupation);
		root.addContent(preOccupation);
		
		Document doc = new Document(root);
		Format format = Format.getPrettyFormat();
		//Format format = Format.getCompactFormat();
		format.setEncoding("utf-8");  //<?xml version="1.0" encoding="utf-8"?>
		XMLOutputter xmlOutputter = new XMLOutputter(format);
		xmlOutputter.output(doc, new FileOutputStream("f:/1.xml"));
	}



转载于:https://my.oschina.net/u/1413786/blog/180538