I'd like to parse this XML file:
<?xml version="1.0"?>
<Gist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../schema/Gist.xsd">
<Name>AboveOrEqualToThreshold</Name>
<Version>1</Version>
<Tags>
<Tag>Comparison</Tag>
</Tags>
<Description>Determines if a value is at or over a threshold or not.</Description>
<Configuration />
<OutputType>
<ScalarType>Boolean</ScalarType>
</OutputType>
<PertinentData>
<Item>
<Name>ValueMinusThreshold</Name>
</Item>
<Item>
<Name>ThresholdMinusValue</Name>
</Item>
</PertinentData>
<Scenarios>
<Scenario>
<ID>THRESHOLD_DOES_NOT_APPLY</ID>
<Description>The threshold does not apply.</Description>
</Scenario>
<Scenario>
<ID>ABOVE_THRESHOLD</ID>
<Description>The value is above the threshold.</Description>
</Scenario>
<Scenario>
<ID>EQUAL_TO_THRESHOLD</ID>
<Description>The value is equal to the threshold.</Description>
</Scenario>
<Scenario>
<ID>NOT_ABOVE_THRESHOLD</ID>
<Description>The value is not above the threshold.</Description>
</Scenario>
</Scenarios>
</Gist>
To get me that value at this XPATH /Gist/Name, so for this file it would be a String:
- AboveOrEqualToThreshold
and the scenarios for this file at this XPATH Gist/Scenarios/Scenario/ID/*, so for this file it would be a list of Strings:
THRESHOLD_DOES_NOT_APPLY
ABOVE_THRESHOLD
EQUAL_TO_THRESHOLD
NOT_ABOVE_THRESHOLD
So the data structure for this would be:
Map<String,List<String>>
How can I accomplish this in Java, this seems pretty straight forward but I am unsuccess in my attempts to get this.
Any help or assistance would be much appreciated.
My implementation attempt:
static Map<Node, Node> parseScenarioByGist(String filename) throws IOException, XPathException {
XPath xpath = XPathFactory.newInstance().newXPath();
Map<Node, Node> scenarioByGist = new LinkedHashMap<Node, Node>();
try (InputStream file = new BufferedInputStream(Files.newInputStream(Paths.get(filename)))) {
NodeList nodes = (NodeList) xpath.evaluate("//Gist", new InputSource(file), XPathConstants.NODESET);
int nodeCount = nodes.getLength();
for (int i = 0; i < nodeCount; i++) {
Node node = nodes.item(i);
Node gist = (Node) xpath.evaluate("Gist/Name", node, XPathConstants.NODE);//String node.getAttributes().getNamedItem("name").getNodeValue();
Node scenario = (Node) xpath.evaluate("Gist/Scenarios/Scenario/ID/*", node, XPathConstants.NODE);
scenarioByGist.put(gist, scenario);
}
}
return scenarioByGist;
}