jdom解析XML的问题

来源:互联网 发布:语义网络 编辑:程序博客网 时间:2024/06/05 07:19

包:jdom.jar与xercesImpl.jar。

下面是摘调后的TEST代码

import java.io.FileNotFoundException;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;/**   * JDOM 生成与解析XML文档  *   */  public class JDomDemo{public void createXml(String fileName) {Document document;   Element  root;   root=new Element("employees");   document=new Document(root);   Element employee=new Element("employee");   root.addContent(employee);   Element name=new Element("name");   name.setText("ddvip");   employee.addContent(name);   Element sex=new Element("sex");   sex.setText("m");   employee.addContent(sex);   Element age=new Element("age");   age.setText("23");   employee.addContent(age);   XMLOutputter XMLOut = new XMLOutputter();     try {XMLOut.output(document, new FileOutputStream(fileName));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {JDomDemo jdom = new JDomDemo();jdom.parserXml("E:\\Work\\xmltest2");}public void parserXml(String fileName) {   SAXBuilder builder=new SAXBuilder(false);      Document document;try {document = builder.build(fileName);//document = builder.build(JDomDemo.class.getClassLoader().getResourceAsStream(fileName));Element employees=document.getRootElement();    List<Element> employeeList=employees.getChildren("employee");for(Element employee : employeeList){System.out.println(employee.getAttribute("name"));System.out.println(employee.getChildText("name"));System.out.println(employee.getText());}} catch (JDOMException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}  


0 0
原创粉丝点击