我有一个提供一组类的第三方库。这些类包含 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/