2010-12-01 64 views
0

我有一个像这样的静态XML。它基本上是一种配置。如何动态读取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放入集合(List,Set等)中,以便元素(DTO)可以很容易搜索?

回答

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

您必须使用XPath表达式。要选择所有foo属性,可以使用'// @ foo'XPath表达式。一旦你拥有了所有的属性,你就可以获得它们的价值。

我不知道在Java中使用的确切语法n类,因为我是C#开发人员。 希望这会帮助你。您可以获得更多关于XPath here的信息。