如何使用JAXB获取xml属性

时间:2013-02-21 10:36:57

标签: java xml-parsing jaxb

这是我的xml:

<?xml version="1.0" encoding="UTF-8" ?>
    <organization>
      <bank>
        <description>aaa</description>
        <externalkey>123</externalkey>
        <property name="pName" value="1234567890" />
      </bank>
   </organization>

我使用JAXB和unmarshall这个xml,我可以得到描述和外键。但我无法获得有价值的物业名称。

  • 这是我的unmarshall java类:

    JAXBContext jb = JAXBContext.newInstance(Organization.class);
    Unmarshaller um = jb.createUnmarshaller();
    Organization org = (Organization) um.unmarshal(new File("\\upload\\bank999999.xml"));
    System.out.println(org.getBank().getDescription());
    System.out.println(org.getBank().getExternalkey());
    
  • Organization.java

    @XmlRootElement
    public class Organization {
    Bank bank = new Bank();
    
    public Bank getBank() {
      return bank;
    }
    
    public void setBank(Bank bank) {
     this.bank = bank;
    }
    }
    
  • Bank.java

    @XmlRootElement
    public class Bank {
     private String description;
     private String externalkey;
     private String property;
    
    //..GETTER and SETTER
    }
    

    我如何获得物业名称和价值?谢谢你

1 个答案:

答案 0 :(得分:6)

<强>银行

您需要将property属性从String更改为域对象。

@XmlAccessorType(XmlAccessType.FIELD)
public class Bank {
    private String description;
    private String externalkey;
    private Property property;
}

<强>属性

然后你的Property对象看起来像:

@XmlAccessorType(XmlAccessType.FIELD)
public class Property {

    @XmlAttribute
    private String name;

    @XmlAtrribute
    private String value;

}