JDom使用示例

读取XML:

public void readXML() {
		try {
			File file = new File("./test.xml");
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(file);
			Element foo = doc.getRootElement();
			List<Object> allChildren = foo.getChildren();
			for (int i = 0; i < allChildren.size(); i++) {
				Element element = ((Element) allChildren.get(i)).getChild("Type");
				String type = element == null ? null : element.getText();
				System.out.println(type);
				element = ((Element) allChildren.get(i)).getChild("Describe");
				String describe = element == null ? null : element.getText();
				System.out.println(describe);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

 

写XML:

public void writeXML() {
		Element rootElt = new Element("Record");
		Element questionElt = new Element("Question");
		Element elt = new Element("Type");
		elt.addContent("type_test");
		questionElt.addContent(elt);
		elt = new Element("Describe");
		elt.addContent("describe_tet");
		questionElt.addContent(elt);
		rootElt.addContent(questionElt);
		Document doc = new Document(rootElt);
		
		XMLOutputter out = new XMLOutputter();

		// 默认UTF-8,这里可以设置
		out.setFormat(Format.getCompactFormat().setEncoding("gb2312"));
		try {
			out.output(doc, new FileOutputStream("./test.xml"));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

  

你可能感兴趣的:(xml)