使⽤dom4j解析xml步骤(基于JAVA)--可直接使⽤总的⽂件⽬录为
第⼀步⾸先要dom4j的jar包等
第⼆步要有相对应的XML⽂件
XML⽂件内容为
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book sn="SN12341232">
<name>辟邪剑谱</name>
<price>9</price>
<author>班主任</author>
</book>
<book sn="SN12341231">
<name>葵花宝典</name>
<price>99</price>
<author>班长</author>
</book>
</books>
第三步创造JAVA类
使用dom4j解析xml文件import java.math.BigDecimal;
public class book {
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public book(String sn, String name, double price, String author) {
this.sn = sn;
this.name = name;
this.price = price;
this.author = author;
}
@Override
public String toString() {
return "book{" +
"sn='" + sn + '\'' +
", name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
public book(String value, String snValue, String nameText, String priceText) {
}
private String sn;
private String name;
private Double price;
private String author;
}
第四步进⾏解析XML⽂件,形成JAVA类
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.util.List;
public class Bookstext {
@Test
public void text2() throws DocumentException {
//1.创建SAXReader对象
SAXReader saxReader = new SAXReader();
//2.读取xml⽂件
Document read = ad("l");
//3.通过Document对象获取根元素
Element rootElement = RootElement();
//4.通过根元素获取book
//element()和elements()都可以获取标签名查⼦元素
List<Element> book = rootElement.elements("book");
//5.遍历,每⼀个book标签转换为Book类
for (Element books:book){
//asXML()把标签对象转化为标签字符串
// Element name = books.element("name");
//getText()可以获取标签中的⽂本内容
// String nameText = Text();
//elementText()可以获取标签名⾥⾯的内容,就不需要像上⾯那样去处理了 String nameText = books.elementText("name");
String priceText = books.elementText("price");
String authorText = books.elementText("author");
//attributeValue()可以获取标签属性的值
String snValue = books.attributeValue("sn");
//这⾥要和声明时的顺序⼀致
System.out.println(new book(snValue,nameText,priceText,authorText)); }
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论