使用jsoup解析xml
上一篇 / 下一篇 2013-01-18 09:25:42 / 个人分类:Java学习
刚接触了点jsoup的东西,貌似可以用来解析xml文件,xml文件格式如下:
<Data>
<BasicInfo>
<Name>KYO</Name>
<Gender>Male</Gender>
<Birthday>26/03/2010</Birthday>
</BasicInfo>
<Address>
<Country>China</Country>
<City>shanghai</City>
<PostalCode>200000</PostalCode>
</Address>
<Comment>
</Comment>
</Data>
代码参考如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
public class XMLOperationByJSoup {
public
String xmlFile;
public
XMLOperationByJSoup(String file) throws Exception{
this.xmlFile
= file;
}
public
Document getXMLDocumentObject() throws Exception{
Document doc
= null;
try{
File input =
new File(xmlFile);
doc =
Jsoup.parse(input, "UTF-8");
} catch
(FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return
doc;
}
//通过xml节点来获取其下的所有属性名
public List getXMLAttributesByNode(String nodeName) throws
Exception{
Document doc
= getXMLDocumentObject();
Elements ele
= doc.getAllElements();
String
strTagName = "";
List arrNode
= new ArrayList();
System.out.println("size=" + ele.size());
for(int
i=0;i
strTagName =
ele.get(i).tagName().trim().toLowerCase();
if(nodeName.toLowerCase().equals(strTagName)){
List list =
ele.get(i).childNodes();
System.out.println("list size=" + list.size());
for(int
j=0;j
String node
= list.get(j).nodeName();
if(!node.equals("#text")){
arrNode.add(node);
}
}
}
}
return
arrNode;
}
//通过xml节点及属性名来获取值
public
String getXMLAttributeValueByNode(String nodeName, String attName)
throws Exception{
Document doc
= getXMLDocumentObject();
Elements ele
= doc.getAllElements();
String
strTagName = "";
String
attValue = "";
System.out.println("size=" + ele.size());
for(int
i=0;i
<Data>
<BasicInfo>
<Name>KYO</Name>
<Gender>Male</Gender>
<Birthday>26/03/2010</Birthday>
</BasicInfo>
<Address>
<Country>China</Country>
<City>shanghai</City>
<PostalCode>200000</PostalCode>
</Address>
<Comment>
</Comment>
</Data>
代码参考如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
public class XMLOperationByJSoup {