XML解析

XML解析方式有两种:

1、DOM解析;
2、SAX解析。
 
XML解析 - darrell - DARRELL的博客
 

 

XML解析 - darrell - DARRELL的博客
 
XML解析 - darrell - DARRELL的博客
 XML解析工具:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class DomUtil {
    /**
     * 读取xml,返回一个Document对象
     * @param path
     * @return
     * @throws Exception
     */
    public static Document getDocument(String path) throws Exception
    {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        return builder.parse(path);
    }
    
    /**
     * 将一个Document文档对象从内存中写入到指定的文件中
     * @param document
     * @param path
     * @throws Exception
     */
    public static void writexml2file(Document document,String path) throws Exception
    {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.transform(new DOMSource(document), new StreamResult(path));
    }

}

public class DomTest {

    /**
     * @param args
     * @throws ParserConfigurationException 
     * @throws IOException 
     * @throws SAXException 
     */
    public static void main(String[] args) throws Exception{

        //1.得到Document
        Document document = DomUtil.getDocument("src/demo.xml");
        //2.创建一个新的批发价结点,并赋内部文本
        Element bookEle = document.createElement("批发价");
        bookEle.setTextContent("18");
        //3.找到第二本,并追加子结点
        Node secondBook = document.getElementsByTagName("books").item(1);
        secondBook.appendChild(bookEle);
        //3.写回xml
        DomUtil.writexml2file(document, "src/books.xml");
    }
}

 

posted @ 2018-01-18 16:23  darrell007  阅读(146)  评论(0编辑  收藏  举报