jai
jai

Reputation: 21907

how to read the xml node value dynamically?

I've a static XML something like this. It is basically a kind of configuration.

<ScoCodes>
    <element scoCode="C1" foo="fooc1" bar="barc1" />
    <element scoCode="C2" foo="fooc2" bar="barc2" />
        <!-- like these 100 nodes are present -->
</ScoCodes>

for a given scoCode, I want to know what is its foo value and bar value?

Since it is static, Do I need to parse once in a static block and convert it to some kind of DTO and put the DTOs in a Collection(List, Set etc) so that the elements(DTOs) can be easily searched?

Upvotes: 0

Views: 1783

Answers (3)

bbcooper
bbcooper

Reputation: 1102

try this

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);

Cheers, Borut

Upvotes: 4

Shekhar
Shekhar

Reputation: 11788

You have to use XPath expressions. To select all the foo attribute you can use '//@foo' XPath expression. Once you have all the attributes, you can get their values.

I dont know exact syntax n classes used in Java to do this as I am C# developer. Hope this will help you. You can get more information about XPath here.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240948

Have a look at this tutorial, It describes how to parse XML file

You can parse XML and store it into list of Objects and make it accessible easily.

Upvotes: 1

Related Questions