我有一个类似这样的静态 XML。它基本上是一种配置。
<ScoCodes>
<element scoCode="C1" foo="fooc1" bar="barc1" />
<element scoCode="C2" foo="fooc2" bar="barc2" />
<!-- like these 100 nodes are present -->
</ScoCodes>
对于给定的scoCode,我想知道它的foo
值和bar
值是什么?
既然它是静态的,我是否需要在静态 block 中解析一次并将其转换为某种DTO并将DTO放入集合(List,Set等)中,以便可以轻松搜索元素(DTO) ?
最佳答案
试试这个
String xmlSource = "your xml";
String xpathExpression = "//element[@scoCode='C1']/@foo | //element[@scoCode='C1']/@bar";
XPath xpath = XPathFactory.newInstance().newXPath();
StringReader reportConfigurationXML = new StringReader(xmlSource);
InputSource inputSource = new InputSource(reportConfigurationXML);
String result = (String) xpath.evaluate(xpathExpression, inputSource, XPathConstants.STRING);
干杯, 博鲁特
关于java - 如何动态读取xml节点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4322503/