Java 根据XPATH批量替换XML节点中的值

简介: Java 根据XPATH批量替换XML节点中的值

根据XPATH批量替换XML节点中的值


测试环境

JDK 1.8.0_25

代码实操

message.xml文件

<Request service="SALE_ORDER_SERVICE" lang="zh-CN">
    <Head>
        <AccessCode>xxxxxxxxxx12Ur8v6qkYAaOf</AccessCode>
        <Checkword>xxxxxxxxxxkmPif7Z35UEJjrR</Checkword>
    </Head>
    <Body>
        <SaleOrderRequest>
            <CompanyCode>Wxxxxxxxxxx</CompanyCode>
            <SaleOrders>
                <SaleOrder>
                    <WarehouseCode>xxxxxxx</WarehouseCode>
                    <ErpOrder>SO20220519xxxx13190</ErpOrder>
                    <ErpOrderType>3</ErpOrderType>
                    <orderType>10</orderType>
                    <receiverAddress>未知地址</receiverAddress>
                    <OrderReceiverInfo>
                        <ReceiverCompany>个人</ReceiverCompany>
                        <ReceiverName>凯琳</ReceiverName>
                        <ReceiverCountry>中国</ReceiverCountry>
                        <ReceiverProvince>广东省</ReceiverProvince>
                        <ReceiverCity>江门市</ReceiverCity>
                        <ReceiverArea>蓬江区</ReceiverArea>
                        <ReceiverAddress>详细地址</ReceiverAddress>
                    </OrderReceiverInfo>
                    <OrderItems>
                        <OrderItem>
                            <SkuNo>1001178</SkuNo>
                            <ItemName>保妇康栓1.74g*14粒/盒</ItemName>
                            <ItemQuantity>1</ItemQuantity>
                        </OrderItem>
                        <OrderItem>
                            <SkuNo>1008766</SkuNo>
                            <ItemName>美团小药箱</ItemName>
                            <ItemQuantity>1</ItemQuantity>
                        </OrderItem>
                    </OrderItems>
                </SaleOrder>
            </SaleOrders>
        </SaleOrderRequest>
    </Body>
</Request>

XMLHelper.java

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
public class XMLHelper {
  // XML文件转XML文档对象
    public static Document xmlFileToDocument(String filePath) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(new File(filePath)));
        return doc;
    }
  // XML文档转XML字符串
    public static String docToString(Document doc) throws TransformerException {
        TransformerFactory ft = TransformerFactory.newInstance();
        Transformer ff = ft.newTransformer();
        ff.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        ff.setOutputProperty("encoding", "gbk");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ff.transform(new DOMSource(doc), new StreamResult(bos));
        return bos.toString();
    }
  // XML字符串转XML文档对象
    public static Document stringToDocument(String xmlData) throws Exception {
        StringReader sr = new StringReader(xmlData);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }
  // 替换单个XPATH指定的XML节点值
    public static void replaceXmlNodeValue(Document doc, String nodePath, String value) throws XPathExpressionException {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        // 匹配需替换的节点
        NodeList nodeList = (NodeList) xpath.evaluate(nodePath, doc, XPathConstants.NODESET);
        // 单个XPATH可能匹配多个XML节点,所以需要遍历替换
        for (int i = 0; i < nodeList.getLength(); i++) {
            nodeList.item(i).setTextContent(value);
        }
    }
  // 批量多个XPATH指定的XML节点值
    public static void replaceXmlNodesValue(Document doc, List<String> nodesPath, String value) throws XPathExpressionException {
        for (String nodePath : nodesPath) {
            XMLHelper.replaceXmlNodeValue(doc, nodePath, value);
        }
    }
    public static void replaceReceiverAddress(Document doc, String value) throws Exception{
        List nodesPath= new ArrayList();
        nodesPath.add(".//OrderReceiverInfo/ReceiverAddress");
        nodesPath.add(".//receiverAddress");
        XMLHelper.replaceXmlNodesValue(doc, nodesPath, value);
    }
  public static void main(String []args) {        
        try {
            Document doc = XMLHelper.xmlFileToDocument("message.xml");
            // 替换地址
            XMLHelper.replaceReceiverAddress(doc, "吉祥街道幸福社区1号大楼23号");
            String newXml = XMLHelper.docToString(doc);
            System.out.println(newXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

文字过少占位符,可无视

目录
相关文章
|
1月前
|
XML JavaScript 数据格式
XML DOM 遍历节点树
XML DOM 遍历节点树
|
9天前
|
分布式计算 Java MaxCompute
ODPS MR节点跑graph连通分量计算代码报错java heap space如何解决
任务启动命令:jar -resources odps-graph-connect-family-2.0-SNAPSHOT.jar -classpath ./odps-graph-connect-family-2.0-SNAPSHOT.jar ConnectFamily 若是设置参数该如何设置
|
28天前
|
XML JavaScript 数据格式
XML DOM 遍历节点树
XML DOM 遍历节点树
|
1月前
|
XML 分布式计算 资源调度
大数据-02-Hadoop集群 XML配置 超详细 core-site.xml hdfs-site.xml 3节点云服务器 2C4G HDFS Yarn MapRedece(一)
大数据-02-Hadoop集群 XML配置 超详细 core-site.xml hdfs-site.xml 3节点云服务器 2C4G HDFS Yarn MapRedece(一)
141 5
|
1月前
|
XML JavaScript 数据格式
XML DOM 遍历节点树
XML DOM 遍历节点树
|
1月前
|
XML 资源调度 网络协议
大数据-02-Hadoop集群 XML配置 超详细 core-site.xml hdfs-site.xml 3节点云服务器 2C4G HDFS Yarn MapRedece(二)
大数据-02-Hadoop集群 XML配置 超详细 core-site.xml hdfs-site.xml 3节点云服务器 2C4G HDFS Yarn MapRedece(二)
79 4
|
1月前
|
分布式计算 资源调度 Hadoop
大数据-01-基础环境搭建 超详细 Hadoop Java 环境变量 3节点云服务器 2C4G XML 集群配置 HDFS Yarn MapRedece
大数据-01-基础环境搭建 超详细 Hadoop Java 环境变量 3节点云服务器 2C4G XML 集群配置 HDFS Yarn MapRedece
68 4
|
1月前
|
分布式计算 Java Hadoop
Hadoop-30 ZooKeeper集群 JavaAPI 客户端 POM Java操作ZK 监听节点 监听数据变化 创建节点 删除节点
Hadoop-30 ZooKeeper集群 JavaAPI 客户端 POM Java操作ZK 监听节点 监听数据变化 创建节点 删除节点
61 1
|
1月前
|
XML JavaScript Java
java与XML文件的读写
java与XML文件的读写
23 3
|
1月前
|
XML JavaScript 数据格式
XML DOM 遍历节点树
XML DOM 遍历节点树
下一篇
无影云桌面