简单的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();
}
}
}对象