Jsoup 可以用于解析、操作HTML,同样也可以用来解析XML,这里只简单介绍一下,更多功能可以查看源码API
package com.hk.internethospital.justtest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.FileReader;
/**
* 利用JSOUP解析XML文件
* Created by libingxian on 2017/4/12.
*/
public class JsoupXmlDemo {
/**
* 从指定文件中读取xml内容
* @param xmlFilePath
* @return
* @throws Exception
*/
public String getXmlStringFromFile(String xmlFilePath) throws Exception{
StringBuilder stringBuilder = new StringBuilder();
FileReader fileReader = new FileReader(xmlFilePath);
BufferedReader bufferedReader= new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine())!= null){
stringBuilder.append(line);
}
return stringBuilder.toString();
}
/**
* 从指定的xml内容中读取对应的元素
* @param xmlStr
*/
public void getXmlElementValue(String xmlStr){
Document document = Jsoup.parse(xmlStr);
Elements elements = document.select("recipe recipename ");
Node node = new DataNode("aaaaa","<asdf>");
for (Element em:elements) {
// em.after(node);
System.out.print("节点名称:" + em.nodeName() + " \n");
Attributes attributes = em.attributes();
for (Attribute at:attributes) {
System.out.print(" -节点属性:" + at + "\n") ;
}
System.out.print(" -节点文本:" + em.text());
System.out.print("\n");
}
}
public static void main(String args[]) throws Exception{
String xmlPath = "";
JsoupXmlDemo jxd = new JsoupXmlDemo();
jxd.getXmlElementValue(jxd.getXmlStringFromFile(System.getProperty("user.dir") + "jsoupxmldemo.xml"));
}
}
xml 内容
<?xml version="1.0" encoding="UTF-8"?>
<recipe type="dessert">
<recipename cuisine="american" servings="1">Ice Cream Sundae</recipename>
<ingredlist>
<listitem><quantity units="cups">0.5</quantity>
<itemdescription>vanilla ice cream</itemdescription></listitem>
<listitem><quantity units="tablespoons">3</quantity>
<itemdescription>chocolate syrup or chocolate fudge</itemdescription></listitem>
<listitem><quantity units="tablespoons">1</quantity>
<itemdescription>nuts</itemdescription></listitem>
<listitem><quantity units="each">1</quantity>
<itemdescription>cherry</itemdescription></listitem>
</ingredlist>
<utensils>
<listitem><quantity units="each">1</quantity>
<utensilname>bowl</utensilname></listitem>
<listitem><quantity units="each">1</quantity>
<utensilname>spoons</utensilname></listitem>
<listitem><quantity units="each">1</quantity>
<utensilname>ice cream scoop</utensilname></listitem>
</utensils>
<directions>
<step>Using ice cream scoop, place vanilla ice cream into bowl.</step>
<step>Drizzle chocolate syrup or chocolate fudge over the ice cream.</step>
<step>Sprinkle nuts over the mound of chocolate and ice cream.</step>
<step>Place cherry on top of mound with stem pointing upward.</step>
<step>Serve.</step>
</directions>
<variations>
<option>Replace nuts with raisins.</option>
<option>Use chocolate ice cream instead of vanilla ice cream.</option>
</variations>
<preptime>5 minutes</preptime>
</recipe>