欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaWeb学习笔记-XML-3

程序员文章站 2022-05-08 13:22:24
...

XML解析:dom&sax

区别
dom:内存消耗大,容易增删改查
sax:内存消耗小,易加载,不适合增删改查

  • XML解析开发包
    – Jaxp(sun)
    – Jdom
    – dom4j

Jaxp

//创建工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInsatnce();
//得到DOM解析器
DocumentBuilder builder = factory.newDocumentBuilder();
//解析XML,得到document
Doucment document = builder.parse("book.xml");
//使用dom方式对xml文档进行curd
//<书名>java</书名>的值
NodeList list = 
document.getElementsByTagName("书名");
Node node = list.item(1);
String content = node.getTextContent();
//得到根节点,循环遍历节点,得到所有标签
Node root = 
Document.getElementsByTagName("书架").item(0);
list(root);
public void list(Node node){
    if(node instanceof Element){
        System.out.prinln(node.getNodeName());
    }
    NodeList list = node.getChildNodes();
    for(int i=0; i<list.getLength(); i++){
        Node child = list.item(0);
        list(child);    
    }
}
//得到标签属性值
//<书名>java</书名>
Element book = (Element)document.getElementsByTagName("书名").item(0);
Steing value = book.getAttribute("name");
//创建节点
Element price = document.createElement("售价");
price.setTextContent("59元");
//把节点挂到第一本书上
Element book = (Element)document.getElementsByTagName("书名").item(0);
book.appendChild(price);
//把内存写入文档
TransformerFactory tffactory = TransformerFactory.newInsance();
Transformer tf = tffactory.newTransfomer();
tf.transform(new DOMSource(document),new StreanResult(new FileOutputStream("book.xml")));
//指定位置添加
//创建节点
Element price = document.createElement("售价");
price.setTextContent("59元");
//得到参考节点
Element refNode = document.getElementsByTagName("售价").item(0);
//得到挂载节点
Element book = (Element)document.getElementsByTagName("书名").item(0);
//往book节点的指定位置插入
book.insertBefore(price,refNode);
//把内存写入文档
TransformerFactory tffactory = TransformerFactory.newInsance();
Transformer tf = tffactory.newTransfomer();
tf.transform(new DOMSource(document),new StreanResult(new FileOutputStream("book.xml")));
//添加name="xxx"属性
Element bookname = (Element)document.getElementsByTagName("书名").item(0);
bookname.setAttribute("name","xxx");
//把内存写入文档
TransformerFactory tffactory = TransformerFactory.newInsance();
Transformer tf = tffactory.newTransfomer();
tf.transform(new DOMSource(document),new StreanResult(new FileOutputStream("book.xml")));
//得到需要删除的节点
Element e = 
(Element)document.getElementsByTagName("售价").item(0);
//得到需要删除节点父节点
Element book = (Element)document.getElementsByTagName("书").item(0);
//删除节点
book.removeChild(e);
//简便方法
//e.getParentNode().removeChild(e);
//更新节点
Element price = 
(Element)document.getElementsByTagName("售价").item(0);
price.setTextContent("22元");