利用Dom4j解析XML

本文详细介绍了如何使用Dom4j进行XML解析,包括从字符串和文件读取XML,通过XPath路径修改元素和属性,获取元素及属性值,删除空属性,以及XML的格式化和写入文件等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、将字符串转换成XML Document

public static Map<String, String> getNameSpace() { //处理命名空间
        Map<String, String> ns = new HashMap<String, String>();
        ns.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
        ns.put("s", "http://calculate.service.com");
        return ns;
    }

public Document loadXmlTemplete(String xmlContent) throws DocumentException, IOException {
        DocumentFactory documentFactory = new DocumentFactory();
        documentFactory.setXPathNamespaceURIs(getNameSpace());
        SAXReader reader = new SAXReader();
        reader.setDocumentFactory(documentFactory);
        InputStream iStream = null;
        try {
            iStream = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("不支持的字符编码类型!", e);
        }
        Document doc = null;
        doc = reader.read(iStream);
        if (iStream != null) {
            iStream.close();
        }
        return doc;
    }

2、根据文件路径读取XML,并得到Document

private Document loadXmlTemplete(String file, Map<String, String> namespaceURIs) throws DocumentException {
        DocumentFactory documentFactory = new DocumentFactory();
        documentFactory.setXPathNamespaceURIs(namespaceURIs);
        SAXReader reader = new SAXReader();
        reader.setDocumentFactory(documentFactory);

        InputStream isFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
        Document doc = reader.read(isFile);
        return doc;
    }

3、根据Xpath路径读取XML,并修改元素值或者属性值

List list = document.selectNodes(xpath);// 元素xpath获取的list
        int size = list.size();
        if (size > 0) {
            if (list.get(index) instanceof Element) {
                Element element = (Element) list.get(index);
                element.setText(value);
            } else if (list.get(index) instanceof Attribute) {
                Attribute attribute = (Attribute) list.get(index);
                attribute.setValue(value);
            }
        }

4、读取元素或者属性的值

public String documentContentGetter(List list, Integer index) {
        String nodeValue = null;
        if (list.get(index) instanceof Element) {
            Element element = (Element) list.get(index);
            nodeValue = element.getTextTrim();
        } else if (list.get(index) instanceof Attribute) {
            Attribute attribute = (Attribute) list.get(index);
            nodeValue = attribute.getValue();
        } else {
            logger.error("找不到匹配的节点类型!");
        }
        return nodeValue;
    }

5、删除属性值为空的属性

List<Attribute> listAttr = element.attributes();
            for (Attribute attr : listAttr) {
                String value = attr.getValue();
                if (StringUtil.isEmpty(value)) {
                    Element attrElement = attr.getParent();
                    attrElement.remove(attr);
                }
            }

6、XML格式美化

/**
     * XML格式美化
     * @param document
     * @throws IOException 
     */
    public String xmlBeautiFormat(Document document) throws IOException{
    	//创建字符串缓冲区 
        StringWriter stringWriter = new StringWriter();  
        //设置文件编码  
        OutputFormat xmlFormat = OutputFormat.createPrettyPrint(); //设置XML文档输出格式  
        xmlFormat.setEncoding("UTF-8"); 
        // 设置换行 
        //xmlFormat.setNewlines(true); 
        // 生成缩进 
        xmlFormat.setIndent(true); 
        // 使用4个空格进行缩进, 可以兼容文本编辑器 
        xmlFormat.setIndent("    "); 
        
        //创建写文件方法  
        XMLWriter xmlWriter = new XMLWriter(stringWriter,xmlFormat);  
        //写入文件  
        xmlWriter.write(document);  
        //关闭  
        xmlWriter.close(); 
        // 输出xml 
        return stringWriter.toString(); 
    }

7、将XML写入到指定路径的文件系统中

/**
	 * 将document写入到指定路径的文件中
	 * 
	 * @param document
	 * @throws IOException
	 */
	public void saveXMLFile(Document document, String filePath) throws IOException {
		// 创建文件输出的时候,自动缩进的格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		// 设置XML字符编码格式
		format.setEncoding("UTF-8");
		// 解决声明下空行问题
		format.setNewLineAfterDeclaration(false);
		// 设置保存到磁盘的XML文件编码格式
		Writer xmlwriter = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
		// 写一个没有格式的XML文件
		XMLWriter write = new XMLWriter(xmlwriter, format);
		write.write(document);
		write.close();
		xmlwriter.close();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值