一、测试XML报文用例
<?xml version="1.0" encoding="UTF-8"?>
<TEST>
<PUB>
<TransSource>ERP</TransSource>
<TransCode>DsbrRpl</TransCode>
<TransSeq>202204081043</TransSeq>
<Version>1.0</Version>
</PUB>
<IN>
<RD>
<ReqSeqID>TEST1202201250001</ReqSeqID>
<RdSeq>TEST00001</RdSeq>
<Reserved1>保留字段1</Reserved1>
<Reserved2>保留字段2</Reserved2>
<Reserved3>保留字段3</Reserved3>
</RD>
<RD>
<ReqSeqID>TEST1202201250002</ReqSeqID>
<RdSeq>TEST00002</RdSeq>
<Reserved1>保留字段1</Reserved1>
<Reserved2>保留字段2</Reserved2>
<Reserved3>保留字段3</Reserved3>
</RD>
</IN>
</TEST>
二、使用代码获取 TEST1202201250002这个值
Document document = null;
try {
document = XmlUtil.readXML(message); //message为xml报文
}catch (Exception e){
throw new LunaBusinessException("请检查报文格式是否合规");
}
String xpath = "//TEST/IN/RD[2]/ReqSeqID"; //RD[2] 代表去匹配第二组RD的同名标签 其他层级的同名标签匹配同理,此处涉及的知识点,请搜索 xpath表达式
String elemValue = XmlUtil.getByXPath(xpath, document, XPathConstants.STRING).toString();
三、效果图
四、总结
xpath表达式使我们可以随心所欲的获得到每个指定标签的值