在了解jaxp中的sax和dom解析模型之后,可以尝试用第三方的jar包来完成xml的解析
下面展示了dom4j的学习的入门文档
参考文档:https://github.com/dom4j/dom4j/wiki/Quick-Start-Guide
可以先参考文档的内容,了解一下dom4j的简单用法,下面我自己写了个入门的程序,发现dom4j的api使用比原生的java的api使用简单很多
1.dom4j实例演示
目标:完成一个xml文件到javabean的转换,需要从xml文件解析出内容,然后封装一个java bean对象,然后输出
- maven的jar依赖
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>
- beans.xml文件
<beans>
<bean id="bean1" class ="com.java.jaxp.dom">
<property name="username">sunkang</property>
</bean>
<bean id="bean2" class ="com.java.jaxp.dom">
<property name="name">sunkang</property>
<property name="username">sunkang</property>
</bean>
</beans>
- java beans的类
/**
* @Project: jdk
* @description: beans对象
* @author: sunkang
* @create: 2018-10-19 09:21
* @ModificationHistory who when What
**/
public class Beans {
public List<Bean> bean;
@Override
public String toString() {
return "Beans{" +
"bean=" + bean +
'}';
}
}
class Bean{
public List<Property> properties;
public String id;
public String clazz;
@Override
public String toString() {
return "Bean{" +
"properties=" + properties +
", id='" + id + '\'' +
", clazz='" + clazz + '\'' +
'}';
}
}
class Property{
public String name ;
public String value;
@Override
public String toString() {
return "Property{" +
"name='" + name + '\'' +
", value='" + value + '\'' +
'}';
}
}
- dom4j解析程序
/**
* @Project: jdk
* @description: dom4j解析
* @author: sunkang
* @create: 2018-10-18 23:28
* @ModificationHistory who when What
**/
public class Dom4jParseXml {
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
String fileUrl = "D:\\Eclipse2018Data\\personProject\\jdk\\java-jaxp\\src\\main\\java\\com\\java\\jaxp\\dom4j\\Beans.xml";
Document document =saxReader.read(fileUrl);
Element root = document.getRootElement();
StringBuffer sbf = new StringBuffer();
Beans beans = new Beans();
beans.bean = new ArrayList<Bean>();
//利用迭代器查找beans元素下的bean的元素
for(Iterator i = root.elementIterator("bean");i.hasNext();){
Bean bean = new Bean();
Element beanElement= (Element) i.next();
String id = beanElement.attributeValue("id");
String clazz = beanElement.attributeValue("class");
bean.id= id;
bean.clazz=clazz;
bean.properties = new ArrayList<Property>();
for(Iterator j = beanElement.elementIterator("property");j.hasNext();){
Property property = new Property();
Element propertyElement= (Element) j.next();
//获取property元素的属性name的值
property.name=propertyElement.attributeValue("name");
property.value = propertyElement.getText();
//添加property实体
bean.properties.add(property);
}
//添加bean实体
beans.bean.add(bean);
}
System.out.println(beans);
}
}
网友评论