Java 如何动态读取xml节点值?
我有一个类似这样的静态XML。它基本上是一种配置Java 如何动态读取xml节点值?,java,xml,xml-parsing,Java,Xml,Xml Parsing,我有一个类似这样的静态XML。它基本上是一种配置 <ScoCodes> <element scoCode="C1" foo="fooc1" bar="barc1" /> <element scoCode="C2" foo="fooc2" bar="barc2" /> <!-- like these 100 nodes are present --> </ScoCodes> 对于给定的scoCode,
<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放入集合(列表、集合等)中,以便轻松搜索元素(DTO)?
您可以解析XML并将其存储到对象列表中,使其易于访问。
您可以解析XML并将其存储到对象列表中,使其易于访问。您必须使用XPath表达式。要选择所有foo属性,可以使用'/@foo'XPath表达式。一旦拥有了所有属性,就可以获得它们的值 我不知道Java中使用的n类的确切语法,因为我是C#开发人员。
希望这对你有帮助。您可以获得有关XPath的更多信息。您必须使用XPath表达式。要选择所有foo属性,可以使用'/@foo'XPath表达式。一旦拥有了所有属性,就可以获得它们的值 我不知道Java中使用的n类的确切语法,因为我是C#开发人员。 希望这对你有帮助。您可以获得有关XPath的更多信息。试试这个
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);
干杯,
Borut试试这个
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);
干杯,
博鲁特