《知识点045:java中xml的dom4j使用场景(4种)》

一、dom4j获取-创建Document对象

DocumentHelper是一个文档助手类(工具类),它可以完成文档、元素、文本、属性、注释、CDATA、Namespace、XPath的创建,以及利用XPath完成文档的遍历和将文本转换成Document。

(一)操作步骤

// 1.1: 读取XML文件,获得document对象
SAXReader reader = new SAXReader();   
Document document = reader.read(new File("input.xml"));


// 1.2:解析XML形式的文本,得到document对象
String text = "<members></members>";
Document document = DocumentHelper.parseText(text);


// 1.3:主动创建document对象
Document document = DocumentHelper.createDocument();   
Element root = document.addElement("members");// 创建根节点

(二)操作例子

/**
     * 遍历新建的xml,将driver、url、username、password的值读取出来
     */
public static void main(String[] args) throws IOException,
DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read("d:/SqlMapConfig.xml");
    List < Element > elements = document.selectNodes("/configuration/environments/environment/dataSource/property");
    String driver = "";
    String url = "";
    String username = "";
    String password = "";
    for (Element e: elements) {
        String name = e.attributeValue("name");
        String value = e.attributeValue("value");
        if ("driver".equals(name)) {
            driver = value;
        } else if ("url".equals(name)) {
            url = value;
        } else if ("username".equals(name)) {
            username = value;
        } else if ("password".equals(name)) {
            password = value;
        }
    }
    System.out.println("driver:" + driver + ",url:" + url + ",username:" + username + ",password:" + password);
}

二、dom4j处理Element节点(获取-添加-删除-查找-设置)

(一)操作步骤

// 1.1:获取文档的根节点.   
Element rootElm = document.getRootElement();


// 1.2:取得某节点的单个子节点.   
Element memberElm=root.element("member");// "member"是节点名


// 1.3:取得节点的文字   
String text=memberElm.getText();//也可以用:
String text=root.elementText("name");//这个是取得根节点下的name字节点的文字.


// 1.4:取得某节点下名为"member"的所有字节点并进行遍历.   
List nodes = rootElm.elements("member"); 
for (Iterator it = nodes.iterator(); it.hasNext();) { 
    Element elm = (Element) it.next(); 
    // do something 
}


// 1.5:对某节点下的所有子节点进行遍历.
for(Iterator it=root.elementIterator();it.hasNext();){ 
    Element element = (Element) it.next(); 
    // do something
}


// 1.6:在某节点下添加子节点.   
Element ageElm = newMemberElm.addElement("age");


// 1.7:设置节点文字.   
ageElm.setText("29");


// 1.8:删除某节点.
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点


// 1.9:添加一个CDATA节点.   
Element contentElm = infoElm.addElement("content");
contentElm.addCDATA(diary.getContent());

(二)操作例子

public void modifyDoc() {
    try {
        Document doc = reader.read(new File("file/catalog.xml"));
        //修改节点内容
        List list = doc.selectNodes("//article");
        Iterator<Element> it = list.iterator();
        while (it.hasNext()) {
            Element el = it.next();
            fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue());
            //修改title元素
            Iterator<Element> elIter = el.elementIterator("title");
            while(elIter.hasNext()) {
                Element titleEl = elIter.next();
                fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue());
                if ("Java configuration with XML Schema".equals(titleEl.getTextTrim())) {
                    //修改元素文本值
                    titleEl.setText("Modify the Java configuration with XML Schema");
                    fail(titleEl.getName() + "#" + titleEl.getText() + "#" + titleEl.getStringValue());
                }
            }
        }

        //修改节点子元素内容
        list = doc.selectNodes("//article/author");
        it = list.iterator();
        while (it.hasNext()) {
            Element el = it.next();
            fail(el.getName() + "#" + el.getText() + "#" + el.getStringValue());
            List<Element> childs = el.elements();
            for (Element e : childs) {
                fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue());
                if ("Marcello".equals(e.getTextTrim())) {
                    e.setText("Ayesha");
                } else if ("Vitaletti".equals(e.getTextTrim())) {
                    e.setText("Malik");
                } 
                fail(e.getName() + "#" + e.getText() + "#" + e.getStringValue());
            }
        }

        //写入到文件
        /*XMLWriter output = new XMLWriter(new FileWriter(new File("file/catalog-modified.xml")));
        output.write(doc);
        output.close();*/
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

三、dom4j处理Element属性(获取-添加-删除-查找-设置)

(一)操作步骤

// 1.取得某节点下的某属性   
Element root=document.getRootElement();
Attribute attribute=root.attribute("size");// 属性名name


// 2.取得属性的文字   
// 也可以用
String text=attribute.getText();   
//  这个是取得根节点下name字节点的属性firstname的值: 
String text2=root.element("name").attributeValue("firstname");


// 3.遍历某节点的所有属性    
Element root=document.getRootElement(); 
for(Iterator it=root.attributeIterator();it.hasNext();){ 
 Attribute attribute = (Attribute) it.next(); 
 String text=attribute.getText(); 
 System.out.println(text); 
}


// 4.设置某节点的属性和文字.    
newMemberElm.addAttribute("name", "sitinspring");


// 5.设置属性的文字   
Attribute attribute=root.attribute("name"); 
attribute.setText("sitinspring");


// 6.删除某属性    
Attribute attribute=root.attribute("size");// 属性名name
root.remove(attribute);

(二)操作例子

public void modifyDoc() {
    try {
        Document doc = reader.read(new File("file/catalog.xml"));

        //修改属性内容
        List list = doc.selectNodes("//article/@level");
        Iterator<Attribute> iter = list.iterator();
        while (iter.hasNext()) {
            Attribute attr = iter.next();
            fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
            if ("Intermediate".equals(attr.getValue())) {
                //修改属性值
                attr.setValue("Introductory");
                fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
            }
        }

        list = doc.selectNodes("//article/@date");
        iter = list.iterator();
        while (iter.hasNext()) {
            Attribute attr = iter.next();
            fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
            if ("December-2001".equals(attr.getValue())) {
                //修改属性值
                attr.setValue("December-2011");
                fail(attr.getName() + "#" + attr.getValue() + "#" + attr.getText());
            }
        }

        //写入到文件
        /*XMLWriter output = new XMLWriter(new FileWriter(new File("file/catalog-modified.xml")));
        output.write(doc);
        output.close();*/
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

四、dom4j操作xml文件方法

(一)dom4j创建xml文件

/**
 * 创建文档
 */
@Test
public void createDocument() {
    //创建一篇文档
    Document doc = DocumentHelper.createDocument();

    //添加一个元素
    Element root = doc.addElement("catalog");
    //为root元素添加注释
    root.addComment("An XML Catalog");
    //添加标记
    root.addProcessingInstruction("target", "instruction");

    //创建元素
    Element journalEl = new BaseElement("journal");
    //添加属性
    journalEl.addAttribute("title", "XML Zone");
    journalEl.addAttribute("publisher", "IBM developerWorks");
    root.add(journalEl);

    //添加元素
    Element articleEl = journalEl.addElement("article");
    articleEl.addAttribute("level", "Intermediate");
    articleEl.addAttribute("date", "December-2001");

    Element titleEl = articleEl.addElement("title");
    //设置文本内容
    titleEl.setText("Java configuration with XML Schema");
    //titleEl.addText("Java configuration with XML Schema");

    Element authorEl = articleEl.addElement("author");
    authorEl.addElement("firstname").setText("Marcello");
    authorEl.addElement("lastname").addText("Vitaletti");

    //可以使用 addDocType() 方法添加文档类型说明。 
    doc.addDocType("catalog", null,"file://c:/Dtds/catalog.dtd"); 

    fail(doc.getRootElement().getName());

    //将xml转换成文本
    fail(doc.asXML());

    //写入到文件
    XMLWriter output;
    try {
        output = new XMLWriter(new FileWriter(new File("file/catalog.xml")));
        output.write(doc);
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

(二)dom4j查找xml文件的内容

public class GetNodes1 {
    /**
     * 将driver、url、username、password的值读取出来
     */
    public static void main(String[] args) throws IOException, DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read("d:/SqlMapConfig.xml");
        Element driverElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='driver']");
        Element urlElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='url']");
        Element usernameElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='username']");
        Element passwordElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
        String driver = driverElement.attributeValue("value");
        String url = urlElement.attributeValue("value");
        String username = usernameElement.attributeValue("value");
        String password = passwordElement.attributeValue("value");

        System.out.println("driver:"+driver+",url:"+url+",username:"+username+",password:"+password);
    }
}

(三)dom4j修改XML文件

public class UpdateNode {
    /**
     * 修改密码为123456
     */
    public static void main(String[] args) throws DocumentException, IOException {
        //读取并修改
        SAXReader reader = new SAXReader();
        Document document = reader.read("d:/SqlMapConfig.xml");
        Element passwordElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
        passwordElement.addAttribute("value", "123456");
        //保存
        OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
        XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
        writer.write(document);
        writer.close();
        os.close();
    }
}

(四)dom4j删除XML文件的某个结点元素

public class DeleteNode {
    /**
     * 删除密码结点
     */
    public static void main(String[] args) throws DocumentException, IOException {
        //找到结点并删除
        SAXReader reader = new SAXReader();
        Document document = reader.read("d:/SqlMapConfig.xml");
        Element passwordElement = (Element) document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
        passwordElement.getParent().remove(passwordElement);

        //保存
        OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
        XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
        writer.write(document);
        writer.close();
        os.close();
    }
}

(五)dom4j删除文档内容

/**
 * <b>function:</b> 删除节点内容
 */
@Test
public void removeNode() {
    try {
        Document doc = reader.read(new File("file/catalog-modified.xml"));
        fail("comment: " + doc.selectSingleNode("//comment()"));
        //删除注释
        doc.getRootElement().remove(doc.selectSingleNode("//comment()"));

        Element node = (Element) doc.selectSingleNode("//article");
        //删除属性
        node.remove(new DOMAttribute(QName.get("level"), "Introductory"));
        //删除元素 节点
        node.remove(doc.selectSingleNode("//title"));

        //只能删除下一级节点,不能超过一级;(需要在父元素的节点上删除子元素)
        Node lastNameNode = node.selectSingleNode("//lastname");
        lastNameNode.getParent().remove(lastNameNode);

        fail("Text: " + doc.selectObject("//*[text()='Ayesha']"));
        Element firstNameEl = (Element)doc.selectObject("//firstname");
        fail("Text: " + firstNameEl.selectSingleNode("text()"));

        //删除text文本
        //firstNameEl.remove(firstNameEl.selectSingleNode("text()"));
        //firstNameEl.remove(doc.selectSingleNode("//firstname/text()"));
        firstNameEl.remove(doc.selectSingleNode("//*[text()='Ayesha']/text()"));

        //删除子元素author
        //node.remove(node.selectSingleNode("//author"));

        fail(doc.asXML());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大大钢琴

喜欢!就请他吃3块钱好吃的吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值