根據XPATH批量替換XML節點中的值 by: 授客 QQ:1033553122 測試環境 JDK 1.8.0_25 代碼實操 message.xml文件 <Request service="SALE_ORDER_SERVICE" lang="zh-CN"> <Head> <AccessCode>x ...
根據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();
}
}
}
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
文字過少占位符,可無視
作者:授客
微信/QQ:1033553122
全國軟體測試QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限於時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額隨意,您的支持將是我繼續創作的源動力,打賞後如有任何疑問,請聯繫我!!!
微信打賞
支付寶打賞 全國軟體測試交流QQ群