java解析xml字符串-jdom

package xml;

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;

public class ReadXmlJdom {
	public static void main(String[] args){
		String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><rsp><user><buyer_credit><level>1</level><score>9</score><total_num>9</total_num><good_num>9</good_num></buyer_credit><nick><![CDATA[honda418]]></nick><sex><![CDATA[m]]></sex></user></rsp>";
		
		StringReader read = new StringReader(xmlStr);
        //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
        InputSource source = new InputSource(read);
        //创建一个新的SAXBuilder
        SAXBuilder sb = new SAXBuilder();
        try {
            //通过输入源构造一个Document
            Document doc = sb.build(source);
            //取的根元素
            Element root = doc.getRootElement();
            System.out.println(root.getName());
            
            List child = root.getChildren();
            Element e = null;
            for (int i = 0; i < child.size(); i++){
            	e = (Element)child.get(i);
            	System.out.println(e.getName());
            }
        }catch(JDOMException e){
        	e.printStackTrace();
        }catch(IOException ioe){
        	ioe.printStackTrace();
        }
	}
}

你可能感兴趣的:(java,xml)