0

How can I read the XML from nested element.

Example:

<main>
    <child>
        <child2>
            <child3>
                <user>
                    <name>John</name>
                </user>
                <user>
                    <name>Doe</name>
                </user>
            </child3>
        </child2>
    <child1>
</main>

Now, I need to construct the user objects from this XML using Jackson. Basically I'm interested from child3 element. I don't want to create main, child1, child2 classes. Directly I want to read from child3. How can I achieve this? Please help

Vasu Youth
  • 323
  • 3
  • 13

1 Answers1

0

You can probably try reading them in MAP class like below,

 XmlMapper xmlMapper = new XmlMapper();
 Map<String,Object> map = xmlMapper.readValue(xml, Map.class);
 Map<String,Object> child1 = (Map<String, Object>) map.get("child1");
 Map<String,Object> child2 = (Map<String, Object>) child1.get("child2");
 Map<String,Object> child3 = (Map<String, Object>) child2.get("child3");

Child3 Map will only contain the data. You will also need to import below maven library to use XMLMapper

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

Another way would be to use JSONNode and then finally deserialize it into child3 object. as shown below,

XmlMapper xmlMapper = new XmlMapper();
ObjectMapper jsonMapper = new ObjectMapper(); //To convert JSON to object
JsonNode  map = xmlMapper.readValue(xml, JsonNode.class);
JsonNode child1 = map.get("child1");
JsonNode child2 = child1.get("child2");
JsonNode child3 = child2.get("child3");
Child3 child3 = jsonMapper.readValue(child3.toString(),Child3.class);
pratap
  • 538
  • 1
  • 5
  • 11
  • But, these two will give the JSON instead of XML. Because of this ```xmlMapper.readValue(child3.toString(),Child3.class)``` is failing with an error: ```Unexpected character '{' (code 123) in prolog; expected '<'``` – Vasu Youth Mar 19 '21 at 06:28
  • Oh yes, you need to use ObjectMapper to convert JSON to Child3 Object. Have modifed the answer above – pratap Mar 19 '21 at 06:44
  • getting an error ```Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token```. Can you please help on this? – Vasu Youth Mar 19 '21 at 07:48
  • looks like Jackson XML mapper has issues while dealing with arrays or tags with similar names in the XML. It replaces the previous one with last one. Please see this thread https://stackoverflow.com/questions/39493173/how-to-convert-xml-to-json-using-only-jackson – pratap Mar 19 '21 at 08:29
  • There is solution as well in that thread on how to handle the duplicate(multiple) elements in the XML – pratap Mar 19 '21 at 08:31