2012-08-01 26 views
1

試圖將我的類映射到xml並添加自定義屬性。jaxb xmlelement使用自定義屬性編組

public class MyXmlMappings { 
    @XmlElement 
    protected String username; 
    @XmlElement 
    protected String password; 
    @XmlElement 
    protected Integer age; 
} 

編組爲XML後看起來是這樣的:

<myXmlMappings> 
<username/> 
<password/> 
<age/> 
</myXmlMappings> 

我需要有這樣的XML:

<myXmlMappings> 
<username type="String" defaultValue="hello" /> 
<password type="String" defaultValue="asdf" /> 
<age type="Integer" defaultValue="25" /> 
</myXmlMappings> 

正如你可以看到我添加的類型和默認值的屬性。如何將它們添加到myXmlMappings類中以便在編組後可見?

向myXmlMappings類添加額外的字段是不可行的我想以某種方式做註釋。

+0

哪裏的默認值從何而來? – 2012-08-01 16:04:38

回答

1

XML表示

我建議以下XML表示:

<myXmlMappings> 
    <xmlMapping name="username" type="String" defaultValue="hello" /> 
    <xmlMapping name="password" type="String" defaultValue="asdf" /> 
    <xmlMapping name="age" type="Integer" defaultValue="25" /> 
</myXmlMappings> 

Java模型

用下面的Java模型:

XmlMa ppings

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class MyXmlMappings { 
    @XmlElement(name="xmlMapping") 
    protected List<XmlMapping> xmlMappings; 

} 

XmlMapping

@XmlAccessorType(XmlAccessType.FIELD) 
public class XmlMapping { 
    @XmlAttribute 
    protected String name; 
    @XmlAttribute 
    protected String type; 
    @XmlAttribute 
    protected String defaultValue; 
} 
1

試試這個:


public class MyXmlMappings { 

    @XmlPath("username/@type") 
    protected String userType; 
    @XmlPath("password/@type") 
    protected String passwordType; 
    @XmlPath("age/@type") 
    protected String ageType; 
    @XmlPath("username/@defaultValue") 
    protected String userDefaultValue; 
    @XmlPath("password/@defaultValue") 
    protected String passwordDefaultValue; 
    @XmlPath("age/@defaultValue") 
    protected Integer ageDefaultValue; 
    @XmlElement 
    protected String username; 
    @XmlElement 
    protected String password; 
    @XmlElement 
    protected Integer age; 
} 
+0

+1 - 此解決方案利用EclipseLink JAXB(MOXy)中的「@ XmlPath」擴展:http://blog.bdoughan.com/2010/07/xpath-based-mapping.html – 2012-08-01 15:47:27