xml-03-Java操作XML

这篇博客介绍了如何使用Java操作XML,包括递归遍历XML文档、创建并写入新的XML文档,以及对已有XML进行读取和修改。示例代码展示了如何创建Document对象、设置和获取节点信息,以及将Document对象写入文件。
摘要由CSDN通过智能技术生成
一、递归遍历整个文档

1.创建Document对象

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 创建文档构建器工厂
DocumentBuilder builder = factory.newDocumentBuilder(); // 通过工厂来获得文档构建器
Document doc = builder.parse(new File("example.xml")); //读取xml文件生成一个document对象

2.递归打印节点名称

public static void printNodeName(Node node,String line){
if(node instanceof Element){
     System.out.println(line + node.getNodeName());
}
if(node.hasChildNodes()){
         NodeList nl = node.getChildNodes();
         for(int i =0;i<nl.getLength();i++){
             printNodeName(nl.item(i),line+"\t");
         }
     }
}

3.完整事例

package xml;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXml {

    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(ReadXml.class.getClassLoader().getResourceAsStream("config.xml"));
        Node nodeList = document.getFirstChild();
        printNodeName(nodeList,"");
    }


    public static void printNodeName(Node node,String line){
        if(node instanceof Element){
            System.out.println(line + node.getNodeName());
        }
        if(node.has
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值