I have the following XML:
<ConfigGroup Name="Replication">
<ValueInteger Name="ResponseTimeout">10</ValueInteger>
<ValueInteger Name="PingTimeout">2</ValueInteger>
<ValueInteger Name="ConnectionTimeout">10</ValueInteger>
<ConfigGroup Name="Pool">
<ConfigGroup Name="1">
<ValueString Encrypted="false" Name="Host">10.20.30.40</ValueString>
<ValueInteger Name="CacheReplicationPort">8899</ValueInteger>
<ValueInteger Name="RadiusPort">12050</ValueInteger>
<ValueInteger Name="OtherPort">4868</ValueInteger>
</ConfigGroup>
<ConfigGroup Name="2">
<ValueString Encrypted="false" Name="Host">10.20.30.50</ValueString>
<ValueInteger Name="CacheReplicationPort">8899</ValueInteger>
<ValueInteger Name="RadiusPort">12050</ValueInteger>
<ValueInteger Name="OtherPort">4868</ValueInteger>
</ConfigGroup>
</ConfigGroup>
</ConfigGroup>
I just wondering what is the simplest way to parse this XML in Java – I want the value from the two host elements (e.g. 10.20.30.40 and 10.20.30.50). Note there may be more than two pool entries (or none at all).
I’m having trouble finding a simple example of how to use the various XML parsers for Java.
Any help is much appreciated.
Thanks!
The simplest way to search for what you are looking for, would be XPath.
The XPath expression
looks for ConfigGroup elements anywhere in your XML, then finds ValueString elements within the ConfigGroup elements, that have a Name attribute with the value “Host”. @Name=Host is like a filter for elements with the name ValueString. And text() at the end, returns the text node of the selected elements.