my_doubt
my_doubt

Reputation: 63

How can i remove an element or attribute from a json output while parsing from xml, using java

{"users": {
    "report": {
        "sub": "eng",
        "score": 30
    },
    "user": {
        "name": "test1",
        "age": 20
    }
}}

my code is:

package project.example;

import org.json.JSONObject; import org.json.XML;

public class Xml2Json {

private static final int PRETTY_PRINT_INDENT_FACTOR = 4;

public static void main(String[] args) {
    
    String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
    JSONObject jsonObject = XML.toJSONObject(xmlString);

system.out.println(jsonObject);

this is the output i got when an xml is parsed to json using java. now i want to remove age=20 from this output.

Could anyone help me to solve this? Thanks in advance!

Upvotes: 2

Views: 1054

Answers (2)

aeberhart
aeberhart

Reputation: 899

If you don't want to use XSLT, this would work as well:

String xmlString =
        "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
jsonObject.getJSONObject("users").getJSONObject("user").remove("age");
System.out.println(jsonObject);

Reading your last comment. you had it almost right. Just the order was wrong. You're traversing the JSON tree from the top.

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163625

Consider preprocessing the XML using XSLT, or post-processing the JSON similarly.

With XSLT 3.0 you can combine the structural transformation and XML-to-JSON conversion into a single operation.

For example (assuming that the structure of your XML is fixed, and only the values vary):

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="json"/>
<xsl:template match="/">
 <xsl:sequence select='
  map{"users": map {
    "report": map {
        "sub": string(/users/report/@sub),
        "score": string(/users/report/@score)
    },
    "user": map {
        "name": string(/users/user/@name)
    }
  }}'/>
</xsl:template>
</xsl:transform>

The advantage of this approach over use of a standard conversion utility like XML.toJSONObject is that you have total control over the JSON that is generated.

Upvotes: 3

Related Questions