JDOM、DOM4j读取XML文件(SAXReader)
<students> <student age="25"><!--如果没有age属性,默认的为20--> <name>崔卫兵</name> <college>PC学院</college> <telephone>62354666</telephone> <notes>男,1982年生,硕士,现就读于北京邮电大学</notes> </student> <student age="26"> <name>cwb</name> <college leader="学院领导">PC学院</college><!--如果没有leader属性,默认的为leader--> <telephone>62358888</telephone> <notes>男,1987年生,硕士,现就读于中国农业大学</notes> </student> </students>
JDOM读取:
SAXBuilder builder = new SAXBuilder(); org.jdom.Document doc = builder.build(new File("F:/xmltest.xml")); Element foo = doc.getRootElement(); List allChildren = foo.getChildren(); for (int i = 0; i < allChildren.size(); i++) { System.out.println( ((Element) allChildren.get(i)).getChild("name").getText()); System.out.println("((Element) allChildren.get(i)).getChild("space").getText()); }
?DOM4J读取XML:
?
public void testRead() throws DocumentException, FileNotFoundException{SAXReader reader=new SAXReader();Document doc=reader.read("D:/myeclipseWorkspace/Struts/src/test.xml");Element root =doc.getRootElement();for(Iterator it=root.elementIterator();it.hasNext();){Element element=(Element)it.next();System.out.println(element.attribute("age").getName()+" == "+element.attribute("age").getValue());System.out.println(element.attributeValue("age"));System.out.println(element.getName());for(Iterator itt=element.elementIterator();itt.hasNext();){//System.out.println(element.attributeValue("age"));Element el=(Element)itt.next();System.out.println(el.getName()+"=="+el.getText()); //getText()获取的是两个标签间的数据如"<name>崔卫兵</name>"中的崔卫兵//getName()获取的是标签名,即“<student age="25"><name>崔卫兵</name>”中的age和name//attributeValue("age")可获取age的值即25}System.out.println("==================");}}
?结果:
?
age == 2525studentname==崔卫兵college==PC学院telephone==62354666notes==男,1982年生,硕士,现就读于北京邮电大学==================age == 2626studentname==cwbcollege==PC学院telephone==62358888notes==男,1987年生,硕士,现就读于中国农业大学==================age == 4545studentname==xxxxxcollege==xxx学院telephone==66666666notes==注视中,注释中==================age == 1212studentname==lxxcollege==yyyy学院telephone==88888888notes==注视中111,注释中222==================
DOM读取XML:
XML文件:
<?xml version="1.0" encoding="gb2312"?><books><book attr="T001" id="idd1"> <name>第一本书</name> <price>$14.09</price></book><book attr="T002" id="idd2"> <name>第二本书</name> <price>$19.89</price></book><book attr="T003" id="idd3"> <name>第三本书</name> <price>$26.00</price></book></books>
?读取:
public void parserXml2(String fileName) {DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();try {DocumentBuilder dombuilder = domfac.newDocumentBuilder();// 方法1Document doc = dombuilder.parse(fileName);/* * 方法2 InputStream is = new FileInputStream("F:\\ABC.xml"); Document * doc = dombuilder.parse(is); *//* * 方法三如果要解析字符串result= * "<?xml version="1.0" encoding="gb2312"?><books><book attribute="T001"><name>第一本书</name><price>$14.09& lt;/price></book><book attribute="T002"><name>第二本书</name><price>$19.89& lt;/price></book><book attribute="T003"><name>第三本书</name><price>$26.00& lt;/price></book></books>" * ;就用此方法 StringReader rd = new StringReader(result); InputSource is * = new InputSource(rd); Document doc=dombuilder.parse(is); */Element root = doc.getDocumentElement();NodeList books = root.getChildNodes();if (books != null) {for (int i = 0; i < books.getLength(); i++) {Node book = books.item(i);if (book.getNodeType() == Node.ELEMENT_NODE) {String attr = book.getAttributes().getNamedItem("attr").getNodeValue();String id = book.getAttributes().getNamedItem("id").getNodeValue();System.out.print(attr+" "+ id);for (Node node = book.getFirstChild(); node != null; node = node.getNextSibling()) {if (node.getNodeType() == Node.ELEMENT_NODE) {if (node.getNodeName().equals("name")) {String name = node.getNodeValue();String name1 = node.getFirstChild().getNodeValue();System.out.print(" " + name);System.out.print(" " + name1);}if (node.getNodeName().equals("price")) {String price = node.getFirstChild().getNodeValue();System.out.println(" " + price);}}}}}}} catch (ParserConfigurationException e) {} catch (FileNotFoundException e) {} catch (SAXException e) {} catch (IOException e) {}}
该实例参考:http://www.360doc.com/content/07/1213/14/13829_891246.shtml
?
二、创建XML
DOM4J创建XML:
/** * 创建XML * @throws Exception */public void testWrite() throws Exception{Document document = DocumentHelper.createDocument();Element root = document.addElement("root"); //根节点for(int i=0;i<10;i++){Element element1 = root.addElement("user").addAttribute("name","Alex"+i).addAttribute("id", "id"+i).addText("我是信息");}XMLWriter writer = new XMLWriter(new FileOutputStream("D:/myeclipseWorkspace/Struts/src/output.xml"));writer.write(document);writer.close();}
?输出方法2:
XMLOutputter XMLOut = new XMLOutputter();File filePath = new File("D:/temp");if (!filePath.exists()) { filePath.mkdirs();}System.out.println("filePath==========="+filePath);XMLOut.output(doc, new FileOutputStream(filePath + "/areaPie.xml"));?
结果:
?
<?xml version="1.0" encoding="UTF-8"?><root><user name="Alex0" id="id0">我是信息</user><user name="Alex1" id="id1">我是信息</user><user name="Alex2" id="id2">我是信息</user><user name="Alex3" id="id3">我是信息</user><user name="Alex4" id="id4">我是信息</user><user name="Alex5" id="id5">我是信息</user><user name="Alex6" id="id6">我是信息</user><user name="Alex7" id="id7">我是信息</user><user name="Alex8" id="id8">我是信息</user><user name="Alex9" id="id9">我是信息</user></root>
?
JDOM创建XML:
import java.io.FileOutputStream; import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.XMLOutputter; public class Java2XML { public void BuildXMLDoc() throws IOException, JDOMException { // 创建根节点 list; Element root = new Element("list"); // 根节点添加到文档中; Document Doc = new Document(root); // 此处 for 循环可替换成 遍历 数据库表的结果集操作; for (int i = 0; i < 5; i++) { // 创建节点 user; Element elements = new Element("user"); // 给 user 节点添加属性 id; elements.setAttribute("id", "" + i); // 给 user 节点添加子节点并赋值; // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui 替换成表中记录值; elements.addContent(new Element("name").setText("xuehui")); elements.addContent(new Element("age").setText("28")); elements.addContent(new Element("sex").setText("Male")); // 给父节点list添加user子节点; root.addContent(elements); } XMLOutputter XMLOut = new XMLOutputter(); // 输出 user.xml 文件; XMLOut.output(Doc, new FileOutputStream("user.xml")); } public static void main(String[] args) { try { Java2XML j2x = new Java2XML(); System.out.println("生成 mxl 文件..."); j2x.BuildXMLDoc(); } catch (Exception e) { e.printStackTrace(); } } } 生成的 user.xml 文件 <?xml version="1.0" encoding="UTF-8"?> <list> <user id="0"> <name>xuehui</name> <age>28</age> <sex>Male</sex> </user> <user id="1"> <name>xuehui</name> <age>28</age> <sex>Male</sex> </user> <user id="2"> <name>xuehui</name> <age>28</age> <sex>Male</sex> </user> <user id="3"> <name>xuehui</name> <age>28</age> <sex>Male</sex> </user> <user id="4"> <name>xuehui</name> <age>28</age> <sex>Male</sex> </user> </list>
?该例子来源:http://zc4530.iteye.com/blog/70062
具体XML操作参见:
http://blog.csdn.net/wlh269/archive/2008/08/31/2855461.aspx
DOM4J? 学习笔记:
http://heavyz.sourceforge.net/homepage/homepage_zh/comp/notes/dom4j.html
?
DOM创建XML方式:
package com.techson.himsnanhwa.admin.web;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class DomDemo{private Document doc;DomDemo() {try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();doc = builder.newDocument();} catch (ParserConfigurationException e) {System.out.println(e.getMessage());}}/** * 都是用 doc.createElement("");创建 * 层次结构使用appendChild(name); 实现 */public void createXml(String fileName) {Element root = doc.createElement("employees");doc.appendChild(root);Element employee = doc.createElement("employee");Element name = doc.createElement("name");name.appendChild(doc.createTextNode("小明"));name.setAttribute("id", "2006414"); //设置idemployee.appendChild(name);Element sex = doc.createElement("sex");sex.appendChild(doc.createTextNode("m"));employee.appendChild(sex);Element age = doc.createElement("age");age.appendChild(doc.createTextNode("30"));employee.appendChild(age);root.appendChild(employee);TransformerFactory tf = TransformerFactory.newInstance();try {Transformer transformer = tf.newTransformer();DOMSource source = new DOMSource(doc);transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");transformer.setOutputProperty(OutputKeys.INDENT, "yes");PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));StreamResult result = new StreamResult(pw);transformer.transform(source, result);System.out.println("生成XML文件成功!");} catch (TransformerConfigurationException e) {} catch (IllegalArgumentException e) {} catch (FileNotFoundException e) {} catch (TransformerException e) {}}public static void main(String[] args){String fileName = "D:\\dom2.xml";DomDemo domDemo = new DomDemo();domDemo.createXml(fileName);}}
?结果:
<?xml version="1.0" encoding="utf-8"?><employees><employee><name id="2006414">小明</name><sex>m</sex><age>30</age></employee></employees>?
?
总结:
Document document=new SAXReader.reader(“xml文路径/文件名xxx.xml”);//得到Document对象或
Element root = new Element("pie");
详解Java解析XML的四种方法:
??? http://developer.51cto.com/art/200903/117512.htm
java中四种操作(DOM、SAX、JDOM、DOM4J)xml方式详解与比较:
?? http://hi.baidu.com/drager_000/blog/item/9ba51937a85c533f0b55a961.html
?
各种属性:
http://yifeng.iteye.com/blog/207239
?