xml解析
import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import cn.wanghaomiao.xpath.model.JXNode;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
/**
* Create Time: 2019年01月23日 14:34
* Create Author: 重庆江小白
**/
public class xml解析 {
/* *//**
* 1、dom4j解析
*//*
@Test
public void dom4j() throws DocumentException {
//创建解析对象new SAXReader()
SAXReader reader = new SAXReader();
//创建文件对象(如果。xml文件在src目录下需要用类加载器)
File file = new File("persons.xml");
//将文件读取到内存中形成dom树
Document document = reader.read(file);
//获取根节点
Element rootElement = document.getRootElement();
//获取根节点的标签名
String name = rootElement.getName();
System.out.println(name);
//获取根节点下一级子节点的集合
List <Element> elements = rootElement.elements();
for (Element element :elements
) {
//获取二级子节点集合
List<Element> elements1 = element.elements();
for (Element element1:elements1
) {
System.out.println(element1.getName()+"--------"+element1.getText());
}
}
//获取根节点的ID
Attribute id = rootElement.attribute("id");
System.out.println(id.getName()+"----"+id.getValue()+"---"+id.getText()+"---"+id.getData());
//根据名字获取字节点
Element person1 = rootElement.element("person1");
System.out.println(person1.getName()+"----"+person1.getText()+"---"+person1.getNodeTypeName()+"---"+person1.getStringValue());
}*/
/**
* 2、Jsoup解析.xml
* @throws IOException
*/
@Test
public void jsoup() throws IOException, XpathSyntaxErrorException {
//获取document对象Jsoup.parse
// Document document = Jsoup.parse(new File("persons.xml"), "UTF-8");
// Elements elements = document.getAllElements();
// System.out.println(elements.get(0));
// Element elementById = document.getElementById("personsId");
// System.out.println(elementById.html());
// System.out.println(elementById.text());
// 获取网络资源
// Document document = Jsoup.parse(new URL("http://222.179.134.225:81/xs_main.aspx?xh=2015210534#a"), 10000);
// Elements allElements = document.getAllElements();
// System.out.println(allElements.get(0));
Document parse = Jsoup.parse(new File("persons.xml"), "utf-8");
JXDocument jxDocument = new JXDocument(parse);
//获取所有的name标签
List<JXNode> jxNodes = jxDocument.selN("//name");
for (JXNode jxNode:jxNodes
) {
System.out.println(jxNode);
}
}
}