package com.wy.xml;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
* xml解析:读取
* @author Dnmngge
*
*/
public class XmlTest {

public static void main(String[] args) throws Exception {
  //1、创建SAXReader对象用于读取xml文件
  SAXReader reader = new SAXReader();
  //2、读取xml文件,得到Document对象
  Document doc = reader.read(new File("src/scores2.xml"));
  //3、获取根元素
  Element root = doc.getRootElement();
  //4、获取根元素下所有子元素
  Iterator<?> it = root.elementIterator();  
  while(it.hasNext()) {
    //取出元素
    Element e = (Element) it.next();
    System.out.println(e.getName());
    //获得id属性
    Attribute id = e.attribute("id");
    System.out.println(id.getName()+"="+id.getValue());
    //获取student的子元素
    Element name = e.element("name");
    Element course = e.element("course");
    Element score = e.element("score");
    //打印
    System.out.println(name.getName()+"="+name.getStringValue());
    System.out.println(course.getName()+"="+course.getText());
    System.out.println(score.getName()+"="+score.getText());
    System.out.println("--------------");
    }
  }

}

 

 

 

package com.wy.xml;

import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* xml解析:创建
* @author Dnmngge
*
*/
public class XmlTest2 {

public static void main(String[] args) throws Exception {
  //1、通过DocumentHelper生成一个Document对象
  Document doc = DocumentHelper.createDocument();
  //2、添加并得到根元素
  Element root = doc.addElement("books");
  //3、为根元素添加子元素
  Element book = root.addElement("book");
  //4、为book元素添加属性
  book.addAttribute("id", "No.1");
  //5、为book添加子元素
  Element name = book.addElement("name");
  Element author = book.addElement("author");
  Element price = book.addElement("price");
  //6、为子元素添加文本
  name.addText("java从入门到放弃");
  author.addText("负能量");
  price.addText("1000");
  //7、格式良好的输出
  OutputFormat format = OutputFormat.createPrettyPrint();
  XMLWriter writer = new XMLWriter(new FileWriter(
  new File("src/book2.xml")), format);
  writer.write(doc);
  //8、释放资源
  writer.close();
  }

}

posted on 2020-04-15 19:39  wylearo  阅读(70)  评论(0编辑  收藏  举报