java - 扩展第三方现有的 JAXB 类

标签 java xml jaxb

我有一个提供一组类的第三方库。这些类包含 XML 结构的对象图,并使用 JAXB 进行 XML(解)编码。假设我有汽车、车轴和轮胎类(class)。

Car 包含 Axle 列表,Axle 包含 Tire 列表。

轮胎看起来像​​

public class Tire {
    private double width;
    private double radius;

    public double getWidth() {
       return width;
    }
    public double getRadius() {
       return radius;
    }
}

现在我想向轮胎添加一个名为压力的属性

public class PressurizedTire extends Tire {
    private double pressure;

    public PressurizedTire(Tire t, double pressure) {
      this.width = t.getWidth();
      this.radius = t.getRadius();
      this.pressure = pressure;
    }
 }

我想使用 JAXB 反序列化包含汽车的 xml 文档,找到所有轮胎并将压力数据添加到每个轮胎。然后我想将消息重新序列化为 XML。目前,编码时额外的属性压力会下降,对象结构会恢复到其原始形式。

向现有 JAXB 模型类添加属性的最佳方法是什么?我不想扩展每个类,并且不确定是否需要重建和修改 .xsd 来实现此目的?

最佳答案

我认为这应该有效

我刚刚尝试过以下类(class):

@XmlAccessorType( XmlAccessType.FIELD )
public class Tire
{
    double width;
    double radius;
}

@XmlRootElement
@XmlAccessorType( XmlAccessType.FIELD )
public class Axle
{
    @XmlElement( name = "tire" )
    List<Tire> tires = new ArrayList<>();
}

@XmlAccessorType( XmlAccessType.FIELD )
public class PressurizedTire extends Tire
{
    double pressure;

    public PressurizedTire( Tire t, double pressure )
    {
        this.width = t.width;
        this.radius = t.radius;
        this.pressure = pressure;
    }
}

以及以下代码

    JAXBContext context = JAXBContext.newInstance( Axle.class, PressurizedTire.class );
    Unmarshaller unmarshaller = context.createUnmarshaller();

    String xml = "<axle><tire><width>2.0</width><radius>1.5</radius></tire><tire><width>2.5</width><radius>1.5</radius></tire></axle>";
    Axle axle = (Axle) unmarshaller.unmarshal( new StringReader( xml ) );

    List<Tire> pressurizedTires = new ArrayList<>();
    for ( Tire tire : axle.tires )
    {
        pressurizedTires.add( new PressurizedTire( tire, 1.0 ) );
    }
    axle.tires = pressurizedTires;

    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    marshaller.marshal( axle, System.out );

并得到这个输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<axle>
    <tire xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="pressurizedTire">
        <width>2.0</width>
        <radius>1.5</radius>
        <pressure>1.0</pressure>
    </tire>
    <tire xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="pressurizedTire">
        <width>2.5</width>
        <radius>1.5</radius>
        <pressure>1.0</pressure>
    </tire>
</axle>

关于java - 扩展第三方现有的 JAXB 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30127264/

相关文章:

java - 用户同时在 JAVA 中执行列表 UI 排序

Java - 模数函数在处理大量数据时失败

xml - 使用 Powershell 更新 Azure 服务配置文件

C# 使用 Object 和 XMLSerializer 添加 XML 属性

java - 将具有不同根元素名称的两个 xml 映射到同一个 java 对象

java - 对从文本文件中提取的数据进行排序

java - 根据对象参数值对 toString 中的对象进行排序

html - 链接到另一个节点中的项目 (XSLT)

Java:我可以使用 JAXB 序列化字符串列表吗?

xsd - 使用不同的命名空间解码 JAXB 子级