簡單的xml咱們能夠經過轉成javaBean實現解析。可是開發中xml通常都是一層嵌套一層的。轉成javaBean明顯是沒法進行解析的。這裏引入Sax解析。html
首先咱們須要jdom.jar,沒有的朋友能夠從這裏下載http://www.jdom.org/news/index.html。java
廢話很少說直接上例子。dom
import java.io.IOException;
import java.io.StringReader;
import java.util.List;ui
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;xml
public class SaxmlStrDemo {
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<submittask tasktypename=\"kind1\" perfrenceNum=\"2\">"+
"<input name=\"張三\" value=\"23\" inputindex=\"1\" perfrence=\"2\">"+
"<input1>李四</input1>"+
"</input>"+"</submittask>";
SaxXml(xml);
}htm
private static void SaxXml(String xml) {
try {
//xml字符串轉成可讀的字符串
StringReader reader = new StringReader(xml);
//建立輸入源
InputSource source = new InputSource(reader);
//sax解析器
SAXBuilder sb = new SAXBuilder();
//經過輸入源構建文檔對象
Document doc = sb.build(source);
//獲取根節點
Element root = doc.getRootElement();
String name = root.getName();
System.out.println("根節點屬性名:"+name);//輸出submittask
/**
* 開發是這個地方是最多見的,通常xml的節點都會攜帶屬性和節點值 --*****
*/
Attribute attribute = root.getAttribute("tasktypename");
System.out.println(attribute.getValue());//輸出kind1
//獲取到根節點下的指定子節點
Element rootChild = root.getChild("input");
System.out.println(rootChild.getName());
//也能夠經過下列方法獲取指定子節點
Element eRootChild=null;
List childrenList = root.getChildren();
for(int i=0;i<childrenList.size();i++){
eRootChild=(Element) childrenList.get(i);
System.out.println(eRootChild.getName());
}
//上面咱們已經獲取到了根節點下面的input節點rootChild,咱們能夠繼續獲取他的子節點,這裏咱們直接根據節點名獲取的
Element inputChild = rootChild.getChild("input1");
String input1_Name = inputChild.getName();
String input1_Value = inputChild.getValue();
System.out.println(input1_Name+"====="+input1_Value);//input1=====李四
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}對象