java-xml操作

1. XML解析方式

    1.1. DOM解析
    1.2. SAX解析
 
2. DOM解析工具
    2.1. DOM解析
            1). JAXP(oracle-sun 官方)
            2). JDOM工具(非官方)
            3).Dom4j工具(非官方)最优推荐
    2.2. SAX解析工具
            1). SAX解析工具(oracle-sun 官网)
 
Dom4j的操作:地址:http://pan.baidu.com/s/1c09bjGk
    1.1 读取xml 
SAXReader reader = new SAXReader();
Document doc = reader.read(new File("./config/person.xml"));
    1.2 读取根元素(.getRootElement())
Element rootElem = doc.getRootElement();
    1.3 获取第一个元素 (.element("标签名"))
Element elem1 = rootElem.element("student");
 
    1.4 获取元素属性值(.attributeValue("属性名"))
Element elem1 = rootElem.element("student");
System.out.println(elem1.attributeValue("id"));
 
    1.5 获取元素单个属性对象(属性对象:attribute("id");属性名:.getName();属性值:.getVale())
Attribute elemAttr1 = elem1.attribute("id");
System.out.println("name:" + elemAttr1.getName() + ",value:" + elemAttr1.getValue());
  1.6 获取元素全部属性对象(①:.attributes();②:. attributeIterator();)
//获取所有属性
List<Attribute> lstAttr = elem1.attributes();
//遍历所有的属性
System.out.println("============遍历所有属性=============");
for (Attribute attribute : lstAttr) {
	System.out.println("name:" + attribute.getName() + ",value:" + attribute.getValue());		
}
System.out.println("============通过Iterator遍历所有属性========");
Iterator<Attribute> it= elem1.attributeIterator();
while (it.hasNext()) {
	Attribute attribute = (Attribute) it.next();
	System.out.println("name:" + attribute.getName() + ",value:" + attribute.getValue());
}
    1.7 获取标签名相同的所有元素(①.elements("student");②.elementIterator("student"))
Element rootElem = doc.getRootElement();
//通过elements,获取list集合
List<Element> lstElem = rootElem.elements("student");
//通过Iterator迭代器,获取相同标签名的所有元素
Iterator<Element> it = rootElem.elementIterator("student");
while (it.hasNext()) {
	Element element = (Element) it.next();
	Student stu = new Student();
	stu.setName(element.elementText("name"));
	stu.setAge(Integer.parseInt(element.elementText("age")));
	stu.setSex(element.elementText("name"));
	stu.setId(Integer.parseInt(element.attribute("id").getValue()));
	lstStudent.add(stu);
}
    1.8 获取元素名和值
Element name = rootElem.element("student").element("name");
/*
<student id="1">
	<name>老牛1</name>
	<age>1</age>
	<sex>男</sex>
</student>
*/
//获取元素的值
System.out.println(name.getText());//打印:老牛
//获取元素的名
System.out.println(name.getName());//打印:name

  

======|根元素(getRootElement())
========|元素(element("student");elements("student");elementIterator("student");
                元素值:getText();元素名:getName();属性值:attributeValue("id"))
==========|属性(attributes();attributeIterator();attribute("id");属性名:getName();
                    属性值:getValue();)
==========|文本
posted @ 2015-11-06 17:34  满天星光  阅读(104)  评论(0)    收藏  举报