Jdom生成xml文件

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"));
	}
相關文章
相關標籤/搜索