编组/解组 XML 列表,其中包含与不同特定变量同名的元素

问题描述 投票:0回答:1

使用 MOXy(或任何其他 XML 框架)是否可以在此 xml 和对象之间执行以下编组和解组:

<teacher>
    <field name="Age">30</field>
    <field name="Name">Bob</field>
    <field name="Course">Math</field>
</teacher>
public class Teacher {
   Field Age;
   Field Name;
   Field Course;
}

public class Field {
    String name;
    String value;
}

有一些适用于编组的解决方案(用

@XmlElement(name= "field")
注释所有字段),也有一些适用于解组的解决方案(
@XmlPath("field[@name='Age']/text()")
.

但是,是否有一种双向工作的解决方案,或者一种可以在这两种格式之间解组和编组 XML 的方法?

xml jaxb moxy
1个回答
0
投票

使用 JAXB 的

xjc
工具从 XML 模式生成 JAXB 类,结果:

xjc -no-header teacher.xsd

老师.java

package generated;

import java.util.*;
import jakarta.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "field" })
@XmlRootElement(name = "teacher")
public class Teacher
{
    @XmlElement(required = true)
    protected List<Field> field;
    public List<Field> getField()
    {
        if (field == null)
            field = new ArrayList<>();
        return this.field;
    }
}

Field.java

package generated;

import jakarta.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "value" })
@XmlRootElement(name = "field")
public class Field
{
    @XmlValue
    protected String value;
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }

    @XmlAttribute(name = "name", required = true)
    protected String name;
    public String getName() { return name; }
    public void setName(String value) { this.name = value; }
}

从此 XML 模式:

老师.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
>

    <xs:element name="teacher">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded" ref="field"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="field">
        <xs:complexType>
            <xs:simpleContent>
                <xs:extension base="xs:string">
                    <xs:attribute name="name" use="required" type="xs:string"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>

</xs:schema>
© www.soinside.com 2019 - 2024. All rights reserved.