简单的xml我们可以通过转成javaBean实现解析。但是开发中xml一般都是一层嵌套一层的。转成javaBean明显是无法进行解析的。这里引入Sax解析。
首先我们需要jdom.jar,没有的朋友可以从这里下载http://www.jdom.org/news/index.html。
废话不多说直接上例子。
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
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;
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);
}
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();
}
}
}