javadev / underscore-java

java port of Underscore.js
https://javadev.github.io/underscore-java/
MIT License
533 stars 80 forks source link

How to create node with value and attribute? #308

Closed javadev closed 3 years ago

javadev commented 3 years ago

I hope it's not a duplicated question, I was looking for an answer for my simple question but I couldn't find anything. I need to convert json to xml using the underscore java library and this is quite easy using U.jsonToXml method. My problem is when I need to create node with value and attribute.

What I can do:

<some_root>
  <ABC some_attribute="attribute">
    <another_tag>some_value</another_tag>
  </ABC>
</some_root>

What I need is:

<some_root>
  <ABC some_attribute="attribute">some_value</ABC>
</some_root>

I was trying different things, playing around with arrays or with self-closing-tag, looking at the gh repo but I couldn't get the node with parameters and value:

"{\"ABC\":{\"-attr\":\"c\", \"value\": \"test\"}}"
"{\"ABC\":{\"-attr\":\"c\", \"-value\": \"test\"}}"

Is there any way to do this? Thanks for your help.

javadev commented 3 years ago

This is an example how to transform xml.

        String xml =
                "<some_root>\n"
                        + "  <ABC some_attribute=\"attribute\">\n"
                        + "    <another_tag>some_value</another_tag>\n"
                        + "  </ABC>\n"
                        + "</some_root>";
        Map<String, Object> data = U.fromXmlMap(xml);
        U.set(data, "some_root.ABC.#text", U.get(data, "some_root.ABC.another_tag"));
        U.remove(data, "some_root.ABC.another_tag");
        String newXml = U.toXml(data);
        assertEquals("<some_root>\n" +
                "  <ABC some_attribute=\"attribute\">some_value</ABC>\n" +
                "</some_root>", newXml);