java中获取xml文件的某个配置节点内容方式
作者:我不想成秃头
这篇文章主要介绍了java中获取xml文件的某个配置节点内容方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
java获取xml文件的某个配置节点内容
如果想要直接获取webconfig.xml里面某个配置文件的节点的内容,如何优雅的实现?
例如有个xml文件如下:
<?xml version="1.0" encoding="UTF-8"?> <webapp-configs> <param name="IP" value="127.0.0.1"/> <param name="PORT" value="8070"/> </webapp-configs>
如何获取PORT的value是多少呢?
下面是代码:
public class WebappConfigUtil { private final static String CONFIG_FILE_NAME = "/webapp-config.xml"; private Document configDocument; private static WebappConfigUtil instance = new WebappConfigUtil();//得到配置文件的document对象 private WebappConfigUtil() { SAXReader reader = new SAXReader();//创建一个读取xml文件的对象 try { configDocument = reader.read(WebappConfigUtil.class .getResourceAsStream(CONFIG_FILE_NAME));//括号内:查找具有给定名称的资源 括号外:得到document对象 } catch (DocumentException exp) { configDocument = DocumentHelper.createDocument(); configDocument.addElement("webapp-configs"); } } public static String getParameter(String name) { //读取wabapp-config.xml的字符串(大标签套小标签) String xpath = "/webapp-configs/param[@name='" + name + "']/@value"; Node node = instance.configDocument.selectSingleNode(xpath);//找到节点 if (node == null) { return ""; } return node.getText(); } public static void main(String[] args){ System.out.println(WebappConfigUtil.getParameter("PORT")); } }
如果想获取参数为name的所有节点的list,那么
public static List<String> getParameterList(String name) { String xpath = "/webapp-configs/param[@name='" + name + "']/list/value"; List<?> nodes = instance.configDocument.selectNodes(xpath); List<String> values = new ArrayList<String>(); for (Iterator<?> iter = nodes.iterator(); iter.hasNext();) { Node node = (Node) iter.next(); values.add(node.getText()); } return values; }
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节点值
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。