java解析XML,
java解析XML,
调用了第三包Org.jdom
Java代码如下
import org.jdom.*;
import org.jdom.input.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* XML解析工具
* @author xiaoliang.zhou
* 2011-4-28
*
*/
public class XmlReader {
private Element rootElement = null;
List result = null;
/**
* 初始化DOM的根
*/
public XmlReader(String xmlFile){
result = new ArrayList();
try {
SAXBuilder builder = new SAXBuilder();//定义解析器
Document doc = null;
doc = builder.build(new FileInputStream(xmlFile));//读取XML文件并解析成document
this.rootElement=doc.getRootElement();//得到XML文件上面的根
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 得到某个特定名称的所有节点内容
* @param codeName节点名称
* @return
*/
public List getElementByCodeName(String codeName){
return this.getElement(this.rootElement, codeName);
}
/**
* 通过根节点得到某个节点的内容
* @param rootElement根节点
* @param codeName节点名称
* @return该节点下的codeName对应的值
*/
private List getElement(Element rootElement,String codeName){
if(rootElement!=null){
List<Element> childs = rootElement.getChildren();
for(Element child:childs){
if(child.getChildren()!=null&&child.getChildren().size()>0){
//说明是父节点
getElement(child,codeName);
}else{
if(child.getName().equals(codeName)){
//找到了相应的节点
this.result.add(child.getTextTrim());
}
}
}
}
return result;
}
public static void main(String [] args){
XmlReader xmlReader = new XmlReader("demo1.xml");
List datas=xmlReader.getElementByCodeName("description");
for(Object obj:datas){
System.out.println(obj);
}
}
}
我的demo1.xml内容如下
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited with XML Spy v2007 (http://www.altova.com) -->
<?xml-stylesheet type="text/xsl" href="demo1.xsl"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
相关文章
- 暂无相关文章
用户点评