import java.io.File;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomTest {
public static void main(String[] args) throws Exception {
//创建一个解析XML文档的对象
//通过工厂模式获取文档构造器
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder db=factory.newDocumentBuilder();
//通过文档构造器获取文档对象
File file=new File("src/books.xml");
Document doc= db.parse(file);
//开始解析doc对象
//读取第一本书的名字
Node books= doc.getFirstChild();
Node book=books.getChildNodes().item(1);
Node name=book.getChildNodes().item(1);
//符合节点操作,拿到name节点,再拿文本节点,再从文本节点中获取节点值
//System.out.println(name.getChildNodes().item(0).getNodeValue());
//是封装了文本的操作,直接从name节点中获取文本的一个方法
System.out.println(name.getTextContent());
//遍历所有的书
//获取所有的书
NodeList list= doc.getElementsByTagName("book");
for (int i = 0; i < list.getLength(); i++) {
Node node= list.item(i);
String bookName=node.getChildNodes().item(1).getTextContent();
System.out.println("第"+(i+1)+"本书名:"+bookName);
}
//修改doc对象
//修改第一本书的价格
book.getChildNodes().item(3).setTextContent("200");
//把修改的过的文档写入xml文件中
//拿转换器 就是把doc写入xml中
Transformer tf=TransformerFactory.newInstance().newTransformer();
File newXML=new File("src/book2.xml");
tf.transform(new DOMSource(doc), new StreamResult(newXML));
}
}
报文内容:
<?xml version="1.0" encoding="utf-8"?>
<books>
<book ID="BH10001" id="BH10001" haha="哈哈">
<name>java学习</name>
<price>100</price>
<author>itany</author>
</book>
<book id="BH10002">
<name>xml</name>
<price>200</price>
<author>itany</author>
</book>
<book id="BH10003">
<name>js</name>
<price>300</price>
<author>itany</author>
</book>
<book id="BH10004">
<name>jsp</name>
<price>400</price>
<author>itany</author>
</book>
<book id="BH10005">
<name>mysql</name>
<price>500</price>
<author>itany</author>
</book>
</books>