XML解析工具类

阅读更多
这是一个接收xml格式的string,并进行解析的工具类。
注:该工具类参考了其他网友的代码,链接忘了。

package com.jackie.mytestproject.xmltest;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * @author jackie
 *
 */
public class XMLBuilder {

	/** xml string */
    private String xmlStr=null;
    /** xml对应的document */
    private Document doc=null;
    /** xml根结点 */
    private Element root=null;
    
    /**
     *构造函数说明:       

*参数说明:@param path

* @throws IOException * @throws SAXException * @throws ParserConfigurationException **/ public XMLBuilder(String xmlStr) throws ParserConfigurationException, SAXException, IOException { this.xmlStr=xmlStr; doc = getDocument(xmlStr); buildRoot(); } public Document getDocument(String xml) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringReader sr = new StringReader(xml); InputSource is = new InputSource(sr); Document doc = builder.parse(is); return doc; } /** * 方法名称:buildRoot

* 方法功能:生成XML的根结点

* 参数说明:

* 返回:void

**/ private void buildRoot() { root=doc.getDocumentElement(); } public NodeList getNodeList() { return root.getChildNodes(); } public Element [] getElementsByName(String name) { List resList=new ArrayList(); NodeList nl=getNodeList(); for(int i=0;i

测试类:

package com.jackie.mytestproject.xmltest;

import org.w3c.dom.Element;

public class XMLBuilderTester {

	public static void main(String[] args) {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("");
			sb.append("");
			sb.append("");
			String xml = sb.toString();
			
			XMLBuilder xmlBl = new XMLBuilder(xml);
			Element[] eList = xmlBl.getElementsByName("Result");
			System.out.println(xmlBl.getElementValue(eList[0]));
			System.out.println(xmlBl.getElementAttr(eList[0], "attr"));
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

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