Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get xml attribute using JAXB

this is my xml:

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

I used JAXB and unmarshall for this xml and I can get description and externalkey. But I cannot get property name with value.

  • This is my java class for unmarshall:

    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
    }
    

    How can I get property name and value? Thank u

like image 291
kamal Avatar asked Feb 21 '13 10:02

kamal


People also ask

How to add attribute in XML using jaxb?

Finally, class UserProfile contains: userId, profileId, name and application elements. 3) As you can see, it's very easy to add an XML attribute to your Java class, just type the annotation “@XmlAttribute” and JAXB will create your attribute automatically.

What is@ XmlAttribute?

The XML attribute is a part of an XML element. The addition of attribute in XML element gives more precise properties of the element i.e, it enhances the properties of the XML element.

How do you add an attribute to an existing XML file in Java?

get your node and simply use this function. ((Element)node). setAttribute("attr_name","attr_value"); then finally update your document.

What is @XmlAttribute in Java?

@Retention(value=RUNTIME) @Target(value={FIELD,METHOD}) public @interface XmlAttribute. Maps a JavaBean property to a XML attribute. Usage. The @XmlAttribute annotation can be used with the following program elements: JavaBean property.


1 Answers

Bank

You need to change the property property from a String to a domain object.

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

Property

Then your Property object would look something like:

@XmlAccessorType(XmlAccessType.FIELD)
public class Property {

    @XmlAttribute
    private String name;

    @XmlAtrribute
    private String value;

}
like image 83
bdoughan Avatar answered Sep 19 '22 10:09

bdoughan