Java dom4j操作xml文件的方法大全

6 篇文章 0 订阅

转自:

Java dom4j操作xml文件的方法大全

下文讲述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测试");
    journalEl.addAttribute("publisher", "发布者");
    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 {   
    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删除文档内容

@Test
public void removeNode() {
    try {
        Document doc = reader.read(new File("file/test.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();
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个问题我可以回答。以下是Java使用dom4j读取XML文件的基本步骤: 1. 导入dom4j的jar包 你可以通过maven或手动下载jar包的方式导入dom4j的jar包。 2. 创建SAXReader对象 SAXReader是dom4j的核心类,用于读取XML文件并将其转换为Document对象。 3. 加载XML文件 使用SAXReader对象的read方法加载XML文件,并将其转换为Document对象。 4. 获取根节点 通过Document对象的getRootElement方法获取XML文件的根节点。 5. 遍历节点 可以使用递归的方式遍历XML文件的节点,获取节点的名称、属性、子节点等信息。 下面是一个简单的示例代码: ```java import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; public class Dom4jDemo { public static void main(String[] args) { try { // 创建SAXReader对象 SAXReader reader = new SAXReader(); // 加载XML文件 Document document = reader.read(new File("example.xml")); // 获取根节点 Element root = document.getRootElement(); // 遍历节点 print(root); } catch (Exception e) { e.printStackTrace(); } } public static void print(Element element) { // 输出节点名称 System.out.println(element.getName()); // 输出节点属性 List<Attribute> attributes = element.attributes(); for (Attribute attribute : attributes) { System.out.println(attribute.getName() + ": " + attribute.getValue()); } // 输出子节点 List<Element> elements = element.elements(); for (Element e : elements) { print(e); } } } ``` 以上是一个简单的dom4j读取XML文件的示例代码,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值