使用单个属性解组空元素

时间:2011-07-29 10:02:39

标签: java jaxb

<animals>
    <dog name="Pluto"></dog>
</animals>

如果想要解组这样的xml,我需要创建动物和狗类 是否有可能只创建一个类?

public class Animals{
    private String dog; // value of this field should be "Pluto"
    private void setDog(String dog);
    private String getDog();
}

我应该如何在动物中注释方法?

2 个答案:

答案 0 :(得分:1)

不,你仍然需要2个类,但你可以隐藏Dog类,并在你的外层暴露相同的方法:

public class Animals{
    private @XmlElement Dog dog; 

    public void setDog(String dogName) {
       dog = new Dog();
       dog.name = dogName;
    }

    public String getDog() {
       return dog.name;
    }


    public static class Dog {
       private @XmlAttribute String name;
    }
}

答案 1 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)负责人,也是JAXB(JSR-222)专家组的成员。

  

是否可以只创建一个班级?

是的,这可以通过几种不同的方式完成:

  1. 使用XmlAdapter
  2. 使用MOXy的@XmlPath扩展程序
  3. 选项1 - XmlAdapter

    此方法与suggested by skaffman类似,只是它保留了域模型的逻辑:

    package forum6871469;
    
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.adapters.XmlAdapter;
    
    public class DogAdapter extends XmlAdapter<DogAdapter.Dog, String> {
    
        @Override
        public Dog marshal(String name) throws Exception {
            Dog dog = new Dog();
            dog.name = name;
            return dog;
        }
    
        @Override
        public String unmarshal(Dog dog) throws Exception {
            return dog.name;
        }
    
        public static class Dog {
    
            @XmlAttribute
            public String name;
        }
    
    }
    

    使用XmlAdapter注释引用@XmlJavaTypeAdaper

    package forum6871469;
    
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
    
    @XmlRootElement
    public class Animals{
        private String dog; // value of this field should be "Pluto"
    
        @XmlJavaTypeAdapter(DogAdapter.class)
        public String getDog() {
           return dog;
        }
    
        public void setDog(String dogName) {
           dog = dogName;
        }
    
    }
    

    了解更多信息

    选项2 - MOXy的@XmlPath扩展

    您可以使用MOXy中的@XmlPath扩展名来映射此用例:

    package forum6871469;
    
    import javax.xml.bind.annotation.XmlRootElement;
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlRootElement
    public class Animals{
        private String dog; // value of this field should be "Pluto"
    
        @XmlPath("dog/@name")
        public String getDog() {
           return dog;
        }
    
        public void setDog(String dogName) {
           dog = dogName;
        }
    
    }
    

    了解更多信息