DOM解析XML

Book.xml源文件

<?xml version="1.0" encoding="UTF-8"?>
<BOOKS>
    <BOOK ID="1001">
        <NAME>三国演义</NAME>
        <PRICE>15</PRICE>
    </BOOK>
    <BOOK ID="1002">
        <NAME>水浒传</NAME>
        <PRICE>14</PRICE>
    </BOOK>
</BOOKS>

Book 实体类,用来new类加载器

public class Book {
}

下面DOM解析XML

//创造DOM解析工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//由解析工厂创造DOM解析对象
DocumentBuilder db = dbf.newDocumentBuilder();
//加载Book.xml文件,类加载器相对路径在Src根目录开始
Book book = new Book();
InputStream stream = book.getClass().getClassLoader().getResourceAsStream("Book.xml");
//由DOM解析对象解析流资源,返回Document对象,Document代表整个XML文档
Document document = db.parse(stream);

解析完XML,进行保存

//创建工厂
TransformerFactory transformerFactory = TransformerFactory.newInstance();
//工厂创建对象
Transformer tf = transformerFactory.newTransformer();
//将Source源转换为Result结果,参数一需要指定Document对象,参数二,需要指定xml路径
tf.transform(new DOMSource(document),newStreamResult("BOOK.xml"));

你可能感兴趣的:(java,android,xml,解析,dom)