使用JAXB解析Java中的xml属性和值

时间:2019-02-06 13:29:06

标签: java xml jaxb unmarshalling

我收到来自REST API的XML响应,如下所示:

 <?xml version="1.0" encoding="UTF-8"?>
 <ns2:testpla xmlns:ns2="http:xyz"  xmlns:ns7="xyz">
 <ns2:category term="Default Category" value="Default Category Value"/>
 <ns2:testase ns7:resource="https://www.cyz.com" units="PH" 
  href="ww.com">XYZ</ns2:testase>
 <ns2:testase ns7:resource="https://ww.cyz.com" units="LH" 
  href="ww.org">AZ</ns2:testase>
 <com.abc xmlns="http://lq.net" extensionDisplayName="QWZ-KEY-TP-TEST-ZWE- 
 TI">
  <div xmlns="http://www.w3.org/1999/xhtml">TriggerA ND confirm the 
 functionality</div>
  </com.abc>
  </ns2:testpla>

我知道如何使用jaxb获取xml元素值(即“ XYZ”)并绑定到bean。但是我坚持知道如何获取资源的值(即“ https://www.cyz.com”),units(“ PH”),href(“ ww.com”),div内xmlns的值?然后将该值映射到对象属性。 请帮助我。

1 个答案:

答案 0 :(得分:0)

分别为testpla和testase创建两个类

Testpla.java

@XmlRootElement(name = "ns2:testpla")
public class Testpla {

    private Testase testase;

    public Testase getTestase() {
        return testase;
    }

    @XmlElement(name = "ns2:testase")
    public void setTestase(Testase testase) {
        this.testase = testase;
    }
}

Testase.java

@XmlRootElement(name = "ns2:testase")
public class Testase {

    private String resource;
    private String units;

    public String getResource() {
        return resource;
    }

    @XmlAttribute(name = "ns7:resource")
    public void setResource(String resource) {
        this.resource = resource;
    }

    public String getUnits() {
        return units;
    }

    @XmlAttribute(name = "units")
    public void setUnits(String units) {
        this.units = units;
    }
}