我有一个像这样的静态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
值是什么?
由于它是静态的,我是否需要在静态块中解析一次并将其转换为某种DTO并将DTO放入Collection(List,Set等)中,以便可以轻松搜索元素(DTO) ?
答案 0 :(得分:4)
试试这个
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);
干杯, 博鲁特
答案 1 :(得分:1)
Have a look at this tutorial, It describes how to parse XML file
您可以解析XML并将其存储到对象列表中,并使其易于访问。
答案 2 :(得分:1)
您必须使用XPath表达式。要选择所有foo属性,可以使用'// @ foo'XPath表达式。拥有所有属性后,您就可以获得它们的值。
我不知道Java中使用的确切语法n类,因为我是C#开发人员。 希望这会帮助你。您可以获得有关XPath here的更多信息。