Demo代码如下:
package com.wenqi.demo; import java.io.IOException; import java.io.StringReader; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.xml.sax.InputSource; /** * @author cwqi * @createTime 2014-9-1 * @version */ public class XmlStringReader { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new XmlStringReader(); } public XmlStringReader(){ String xmlString="<ocs_result><callInfo_details><CallInfo projId=‘8‘ sampleId=‘6‘ called=‘004‘ callStatus=‘2‘ statusTimeLength=‘4294967290‘ redailTimes=‘0‘ /></callInfo_details></ocs_result>"; //创建一个新的字符串 StringReader read = new StringReader(xmlString); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); //创建一个新的SAXBuilder SAXBuilder saxbBuilder = new SAXBuilder(); try { //通过输入源构造一个Document Document doc = saxbBuilder.build(source); //取的根元素 Element root = doc.getRootElement(); System.out.println(root.getName()); List<?> node = root.getChildren(); for (int i = 0; i < node.size(); i++) { Element element=(Element)node.get(i); System.out.println(element.getName()); List<?> subNode = element.getChildren(); for(int j=0;j<subNode.size();j++){ Element subElement=(Element)subNode.get(j); System.out.println(subElement.getName()); System.out.println("projId:"+ subElement.getAttributeValue("projId")); System.out.println("sampleId:"+ subElement.getAttributeValue("sampleId")); System.out.println("called:"+ subElement.getAttributeValue("called")); System.out.println("callStatus:"+ subElement.getAttributeValue("callStatus")); System.out.println("statusTimeLength:"+ subElement.getAttributeValue("statusTimeLength")); System.out.println("redailTimes:"+ subElement.getAttributeValue("redailTimes")); } } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-10-06 08:32:49