1

I have a simple XML file that has the following structure

<?xml version = "1.0" encoding = "UTF-8"?>
<EXPORT id="0" >
    <PUB id="1">
        <PGR id="2" name="siblingparent" >
            <PGR id="3" name="sibling1"/>
            <PGR id="4" name="sibling2"/>
        </PGR>
    </PUB>
</EXPORT>

I have this test to see if Jackson's XmlMapper using the readTree() method will parse the file as JsonNode correctly.

  @Test
  public void test() throws IOException {
    JsonNode node = parser.getNodeFromXML(siblingXML.getFile());
    assertThat(node.findValues("PGR")).size().isEqualTo(3);
  }

The test fails because only 1 PGR element has been found.

This is the logic for parser.getNodeFromXML:

  public JsonNode getNodeFromXML(File xmlFile) throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    return xmlMapper.readTree(xmlFile);
  }

And this is how the JsonNode Object / the variable node in the test is returned:

{
  "id": "0",
  "PUB": {
    "id": "1",
    "PGR": {
      "id": "2",
      "name": "siblingparent",
      "PGR": {
        "id": "4",
        "name": "sibling2"
      }
    }
  }
}

As you can see only sibling2 to has been parsed by the XmlMapper. I already looked for flags to allow siblings or whatever. Was not able to find a solution yet. May I misunderstand what a Tree is here? Does it ignore siblings on purpose?

xetra11
  • 7,671
  • 14
  • 84
  • 159
  • Not entirely sure, but it could have something to do with duplicate same-level keys. In theory JSON allows that, but it would make sense to assume many serialization frameworks would prohibit it. See [here](https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object) for reference. – Mena Oct 17 '19 at 10:23
  • [Also related](https://github.com/FasterXML/jackson-core/issues/60) – Mena Oct 17 '19 at 10:26
  • @Mena remove dot from the last link – Vault23 Oct 17 '19 at 10:28
  • 1
    `JsonNode` is not able to handle many properties with the same name. You need to introduce manual deserialisation or provide `POJO` class which fits your `XML` payload. Take a look on similar questions: [Cannot deserialize unwrapped list ...](https://stackoverflow.com/questions/54597977/cannot-deserialize-convert-unwrapped-list-when-its-second-in-class-using-jack), [Using Jackson to add XML attributes to manually-built node-tree](https://stackoverflow.com/questions/57060797/using-jackson-to-add-xml-attributes-to-manually-built-node-tree) – Michał Ziober Oct 17 '19 at 10:43
  • Ok I understand. I was trying to reenable the duplicates but was not able to do so using the `XmlMapper#enable` method. It has a lot of features including exception throwing when a duplicate key occurs but unfortunately no way to disable it :( – xetra11 Oct 17 '19 at 11:40

0 Answers0