java根据xml节点地址获取指定节点内容

备好几个前同事问过怎么获取xml指定节点内容后,终于决定写个工具类,今天特地分享给大家,写的不好,不要喷

maven依赖包

<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

  


XmlUtil

import java.util.*;
import java.util.stream.Collectors;

import org.dom4j.*;

public class XmlUtil {

/**
* 获取XML指定节点内容
* @param xml xml内容
* @param attrName 节点名称(例如:TranData.OutputData.Result)
* @return
* @throws Exception
*/
public static String getXmlAttrValue(String xml,String attrName) throws Exception {
if (null==xml||xml.equals("")||null==attrName||attrName.equals("")){
return null;
}
String[] attrs = attrName.split("\\.");
int length = attrs.length;
String result = null;
// 将xml格式字符串转化为DOM对象
Document document = DocumentHelper.parseText(xml);
// 获取根结点对象
Element element = document.getRootElement();
List<Element> elements = Arrays.asList(element);
for (int i = 0; i < length; i++) {
Map<String,Element> elementMap = elements.stream().collect(Collectors.toMap(e->e.getName(),e->e));
if (elementMap.containsKey(attrs[i])){
if (i==length-1){
result = elementMap.get(attrs[i]).asXML();
break;
}else {
elements = elementMap.get(attrs[i]).elements();
}
}else {
throw new Exception("Node does not exist:"+attrName);
}
}
return result;
}
}

  

测试代码

public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
"<TranData>\n" +
" <ClientInfo>\n" +
" <resultCode>0</resultCode>\n" +
" <resultMsg>查询成功</resultMsg>\n" +
" <transDate>2023-08-30</transDate>\n" +
" </ClientInfo>\n" +
" <InputData>\n" +
" <PolicyNum>321052800581541</PolicyNum>\n" +
" </InputData>\n" +
" <OutputData>\n" +
" <Result>\n" +
" <SubPolBackFee>111.52</SubPolBackFee>\n" +
" <InceptContValue>0</InceptContValue>\n" +
" <OtherDeduct>1430.48</OtherDeduct>\n" +
" <AccountChg>0</AccountChg>\n" +
" <CashValue>1542.00</CashValue>\n" +
" <BankCode>103</BankCode>\n" +
" <BankCodeName>中国农业银行</BankCodeName>\n" +
" <BankAccNo>6228480320236711910</BankAccNo>\n" +
" <AccName>快快快</AccName>\n" +
" <SumPrem>1542</SumPrem>\n" +
" <SumAmnt>100000</SumAmnt>\n" +
" <PayCount>1</PayCount>\n" +
" <LiveInsuaccMoney>0.0</LiveInsuaccMoney>\n" +
" <BonusInsuaccMoney>0.0</BonusInsuaccMoney>\n" +
" <LoanAmnt></LoanAmnt>\n" +
" <LoanInterest></LoanInterest>\n" +
" </Result>\n" +
" </OutputData>\n" +
"</TranData>\n";
String result = getXmlAttrValue(xml,"TranData.OutputData.Result.BankCodeName");
System.out.println(result);
}

  

测试结果输出

 

 

 

另外,如果要获取xml节点得值可以修改代码,

Element.getText()、Element.getStringValue()都可以获取xml节点值

posted on 2023-01-09 13:39  云淡风轻博客  阅读(1006)  评论(0编辑  收藏  举报