码迷,mamicode.com
首页 > 编程语言 > 详细

Java 使用jaxp删除节点

时间:2016-12-12 13:46:11      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   ted   import   cto   int   instance   result   exception   ati   

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person>
    <p1>
        <name>jobs</name>
        <age>56</age>
        <sex>male</sex>
    </p1>
    <p1>
        <name>Alis</name>
        <age>32</age>
    </p1>
</person>
package jaxp;

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;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;


public class TestJaxp {
    public static void main(String[] args) {
        try {
            deleteSex();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void deleteSex() throws Exception{
        //创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //创建解析器
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        //解析xml返回document
        Document document = document = builder.parse("src/person.xml");
        
        // 得到sex
        Node sex = document.getElementsByTagName("sex").item(0);
        //得到父节点
        Node p1 = sex.getParentNode();
        //删除子节点
        p1.removeChild(sex);
        // 回写xml
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult("src/person.xml"));
    }
    
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person>
    <p1>
        <name>jobs</name>
        <age>56</age>
        
    </p1>
    <p1>
        <name>Alis</name>
        <age>32</age>
    </p1>
</person>

 

Java 使用jaxp删除节点

标签:style   ted   import   cto   int   instance   result   exception   ati   

原文地址:http://www.cnblogs.com/lantu1989/p/6163880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!