如何使用java解析XML下面?

时间:2018-03-15 07:32:24

标签: java json

Iam尝试使用java 1.7

获取状态和消息标记信息

请指导我, 提前致谢

<API version="0.0">
  <response>
    <operation name="ADD">
      <result>
        <statuscode>200</statuscode>
        <status>Success</status>
        <message> successfully</message>
      </result>
      <Details type="ADD"/>
    </operation>
  </response>
</API>

1 个答案:

答案 0 :(得分:0)

这不是你得到的JSON响应,它是一个XML响应, 您只需将XML响应转换为POJO类并改为使用POJO类。

以下是POJO类的外观

public class MyPojo{

    private API API;

    public API getAPI() {
        return API;
    }

    public void setAPI(API API) {
        this.API = API;
    }
}

现在MyPojo将包含另一个名为API的类

public class API {

    private Response response;
    private String version;

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

现在API类包含另一个名为Response

的类
public class Response {

    private Operation operation;

    public Operation getOperation() {
        return operation;
    }

    public void setOperation(Operation operation) {
        this.operation = operation;
    }
}

现在,Response类包含另一个名为Operation

的类
public class Operation {

    private Result result;
    private Details Details;
    private String name;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Details getDetails() {
        return Details;
    }

    public void setDetails(Details Details) {
        this.Details = Details;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

现在你猜对了,Operation类包含两个类Details和Result

以下是包含您要访问的状态和消息的Result类

public class Result {

    private String message;
    private String status;
    private int statuscode;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getStatuscode() {
        return statuscode;
    }

    public void setStatuscode(int statuscode) {
        this.statuscode = statuscode;
    }
}

这是Details类

public class Details {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

最后,您可以通过从MyPojo类创建对象来访问状态和消息,如下所示:

String message = myPojo.getAPI().getResponse().getOperation().getResult().getMessage();

String status = myPojo.getAPI().getResponse().getOperation().getResult().getStatus();

您可以使用this在线转换器将XML / JSON转换为POJO。

我希望我的回答很有帮助:)