编程语言
首页 > 编程语言> > Java 根据XPATH批量替换XML节点中的值

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

作者:互联网

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

by: 授客 QQ:1033553122

测试环境

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();
        }
       
    }
}

文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视
文字过少占位符,可无视

标签:XPATH,XML,Java,xml,doc,import,Document,javax
来源: https://www.cnblogs.com/shouke/p/16663766.html