事先需要从这里下载:http://www.jdom.org/dist/binary/ jdom api,导入build目录的 jdom.jar
JdomRWXML.java 源码:
java代码
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.List;
-
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.input.SAXBuilder;
- import org.jdom.output.XMLOutputter;
-
- public class JdomRWXML {
- public void BuildXMLDoc() throws IOException, JDOMException {
-
- Element root = new Element("list");
-
- Document Doc = new Document(root);
-
- for (int i = 0; i < 5; i++) {
-
- Element elements = new Element("company");
-
- elements.setAttribute("id", "" + i);
-
- elements
- .addContent(new Element("company_name").setText("name" + i));
- elements.addContent(new Element("company_email").setText("name" + i
- + "@163.com"));
-
- root.addContent(elements);
- }
- XMLOutputter XMLOut = new XMLOutputter();
-
- XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
- }
-
- public void ReadXMLDoc() throws IOException, JDOMException {
- SAXBuilder sb = new SAXBuilder();
- Document doc = sb.build(new FileInputStream("company_list.xml"));
- Element root = doc.getRootElement();
- List<?> list = root.getChildren();
- for (int i = 0; i < list.size(); i++) {
- System.out.println("---------------------------");
- Element item = (Element) list.get(i);
- String id = item.getAttribute("id").getValue();
- System.out.println("id-->" + id);
-
- Element sub1 = item.getChild("company_name");
- String company_name = sub1.getText();
- System.out.println("company_name-->" + company_name);
-
- Element sub2 = item.getChild("company_email");
- String company_email = sub2.getText();
- System.out.println("company_email-->" + company_email);
- }
-
- }
-
-
-
-
- public static void main(String[] args) {
-
- try {
- JdomRWXML jdomRWXML = new JdomRWXML();
-
- System.out.println("--------BuildXMLDoc----------");
- jdomRWXML.BuildXMLDoc();
-
- System.out.println("--------ReadXMLDoc----------");
- jdomRWXML.ReadXMLDoc();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- }