JAVA解析XML 和 python 解析 XML 两者的异同

python xml.dom API 文档
java org.w3c.xml API 文档

此处涉及 xml 解析,并写入到新的文件中

模板文件

<?xml version="1.0" encoding="UTF-8"?>
<Appconfig scanPeriod="1 seconds">
    <ClientConfig>
        <Download>
            <Directory task="download-black_dragon" count="100">
                <Server>/data/sftp/mwlsftp/download</Server>
                <Local>E:\\sftp\\download\\black_dragon</Local>
                <LocalTemp>E:\\sftp\\temp\\download</LocalTemp>
            </Directory>
            <Directory task="download-black_dragon" count="100">
                <Server>/data/sftp/mwlsftp/download/test2</Server>
                <Local>E:\\sftp\\download\\black_dragon\\test2</Local>
                <LocalTemp>E:\\sftp\\temp\\download</LocalTemp>
            </Directory>
        </Download>
    </ClientConfig>
</Appconfig>

pyhon 解析 xml 代码

import xml.dom.minidom as minidom
import codecs
from xml.dom.minidom import Element

tree = minidom.parse('config.xml')
# 获取父节点
item = tree.getElementsByTagName('Download').item(0)
dom = minidom.Document()
# 遍历子节点
for child in item.childNodes:
    # 当子节点是 Element 类型 进行赋值
    if isinstance(child, Element):
        # 设置属性值
        child.setAttribute('name', 'black-dragon')
        child.appendChild(dom.createTextNode('\t'))
        # 获取结点文本
        serverNodeList = child.getElementsByTagName('Server')
        serverValue = serverNodeList[0].childNodes[0].data + \
            'black-dragon'
        childElement = dom.createElement(tagName='newTag')
        child.appendChild(childElement)
        childElement_text = dom.createTextNode(serverValue)
        childElement.appendChild(childElement_text)
        child.appendChild(childElement)
        child.appendChild(dom.createTextNode('\r\n\t\t\t'))
f = codecs.open('newFileName.xml', 'w', encoding='utf-8')
tree.writexml(f, encoding='utf-8')

Java 解析 xml 代码

package com.blackdragon.sftp.utils;

import org.springframework.boot.system.ApplicationHome;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author black-dragon
 * @version V1.0
 * @Package com.blackdragon.sftp.utils
 * @date 2022/11/22
 * @Copyright
 */
public class XMLAnalysis {
    public static void main(String[] args) {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        FileOutputStream fileOutputStream = null;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
            ApplicationHome home = new ApplicationHome(FilePropertiesReadUtils.class);
            File file = new File(home.getDir().getAbsolutePath() + "\\properties\\config.xml");
            file.getTotalSpace();
            Document doc = docBuilder.parse(file);
            // 获取父节点
            NodeList listOfTagName = doc.getElementsByTagName("Download");
            Element tagNameNode = (Element) listOfTagName.item(0);
            NodeList listOfServer = tagNameNode.getChildNodes();
            // 遍历子节点
            for (int i = 0; i < listOfServer.getLength(); i++) {
                Node firstBookNode = listOfServer.item(i);
                // 判断类型是否是 ELEMENT_NODE
                if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) firstBookNode;
                    // 新增属性值
                    element.setAttribute("name", "black_dragon");
                    // 获取 Server Node 值
                    NodeList nodeList = element.getElementsByTagName("Server");
                    Element firstNameElement = (Element)nodeList.item(0);
                    NodeList textFNList = firstNameElement.getChildNodes();
                    String serverValue = (textFNList.item(0)).getNodeValue().trim();
                    System.out.printf(serverValue);
                    // 新建 Node
                    Element newTag = doc.createElement("newTag");
                    // 添加文本 Node
                    Text textNode = doc.createTextNode(serverValue + "_black");
                    firstBookNode.appendChild(newTag);
                    newTag.appendChild(textNode);

                }
            }
            // 写入到新的文件中
            fileOutputStream = new FileOutputStream(home.getDir().getAbsolutePath() + "\\properties\\newFile.xml");
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            DOMSource domSource = new DOMSource(doc);
            StreamResult streamResult = new StreamResult();
            streamResult.setOutputStream(fileOutputStream);
            transformer.transform(domSource, streamResult);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

两种方法处理结果是一样的

<?xml version="1.0" encoding="utf-8"?><Appconfig scanPeriod="1 seconds">
    <ClientConfig>
        <Download>
            <Directory task="download-black_dragon" count="100" name="black-dragon">
                <Server>/data/sftp/mwlsftp/download</Server>
                <Local>E:\\sftp\\download\\black_dragon</Local>
                <LocalTemp>E:\\sftp\\temp\\download</LocalTemp>
            	<newTag>/data/sftp/mwlsftp/downloadblack-dragon</newTag>
			</Directory>
            <Directory task="download-black_dragon" count="100" name="black-dragon">
                <Server>/data/sftp/mwlsftp/download/test2</Server>
                <Local>E:\\sftp\\download\\black_dragon\\test2</Local>
                <LocalTemp>E:\\sftp\\temp\\download</LocalTemp>
            	<newTag>/data/sftp/mwlsftp/download/test2black-dragon</newTag>
			</Directory>
        </Download>
    </ClientConfig>
</Appconfig>

总结

  1. Python 代码相对简洁,但是传参及返回值需要一步步查看源码才知道。
  2. Java 代码复杂,但是在一些错误检查上比 Python 更快。
    以上的代码只给出了少数的注释,大部分接口方法需要自己查看文档然后结合案例具体熟悉使用。如有疑问可评论留言
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值