I have a simple xml file structured like this with multiples B keys
<?xml version="1.0" encoding="UTF-8"?>
<Example>
<ExampleId>0000</ExampleId>
<Name>test</Name>
<Important1>
<Id>
<Number>1111111111</Number>
</Id>
</Important1>
<B>
<Name>test2</Name>
<Important2>
<Id>
<Number>2222222222</Number>
</Id>
</Important2>
</B>
<B>
<Name>test3</Name>
<Important2>
<Id>
<Number>3333333333</Number>
</Id>
</Important2>
</B>
</Example>
I need to retrieve all values from Number keys to a List
I tried multiple ways
JsonNode numberParser = xmlMapper.readTree(inputStream);
JsonNode node1 = numberParser.get("Example");
//first try
List<String> list =node1.findValuesAsText("Number");
//second try
List<String> list =new ArrayList<String>();
node1.fields().forEachRemaining(firstEntry -> {
if(firstEntry.getKey().equals("Important1")){
JsonNode fieldsNode = firstEntry.getValue();
String numberFromImportant1 = fieldsNode.findValue("Number").asText();
list.add(numberFromImportant1);
}
if(firstEntry.getKey().equals("B")){
JsonNode fieldsNode = firstEntry.getValue();
String numberFromImportant2 = fieldsNode.findValue("Number").asText();
list.add(numberFromImportant2);
}
});
However , it seems that jackson takes only the last value from Number if it encounters duplicate B nodes while deserializing Any way to prevent that and allow Jackson to take duplicate into account as well ?
If all you want to do is retrieve the value for the node
number, then consider using xpath. Appending double forward space to the XML node will search for the node (in the entire xml file). E.g: //Number
For example:
Document xmlDocument = builder.parse(inputStream);
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Number";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);