我有pointbrush
类,这个类包含对象属性colorPoint
这个属性类型是Color
。我使用JAXB
用于生成我的所有类,但我的问题是如何在 XML
中存储 Color 属性而不生成类 Color,因为 JAVA
有这个类并且我使用了这个类,所以我不'其他时间不想要一代。
在我的架构中:
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/ProjectDataBase"
<complexType name="PointBrush">
<element name="ColorPoint" type="string" maxOccurs="1"
minOccurs="1">
</element>
<element name="ColorPoint" type="tns:ColorPoint" maxOccurs="1"
minOccurs="1">
</element>
</complexType>
<complexType name="ColorPoint">
<sequence>
<element name="r" type="float" maxOccurs="1" minOccurs="1"></element>
<element name="g" type="float" maxOccurs="1" minOccurs="1"></element>
<element name="b" type="float" maxOccurs="1" minOccurs="1"></element>
<element name="t" type="float" maxOccurs="1" minOccurs="1"></element>
</sequence>
</complexType>
</schema>
Java 代码:
public class PointBrush {
@XmlElement(name = "ColorPoint")
protected Color colorPoint;
public Color getColorPoint() {
return colorPoint;
}
public void setColorPoint(Color value) {
this.colorPoint = value;
}
}
public class BrushPointMr{
public boolean Insert(PointBrush entity) {
jaxbContext = JAXBContext.newInstance(Project.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Project project = (Project) jaxbUnmarshaller.unmarshal(file);
PointBrush newBrush = objectFactory.createPointBrush();
newBrush.setColorPoint(entity.getColorPoint());
////what can I do in java code for store object Color///////
}
}
最佳答案
从 XML 架构开始
您可以使用外部绑定(bind)文件来配置 XJC 来执行您想要的操作。在下面的示例中,现有类 com.example.Foo
将用于名为 Foo
的复杂类型。
绑定(bind).xml
<jxb:bindings
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
version="2.1">
<jxb:bindings schemaLocation="yourSchema.xsd">
<jxb:bindings node="//xs:complexType[@name='ColorPoint']>
<jxb:class ref="java.awt.Color"/>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
XJC 通话
xjc -d outputDir -b binding.xml yourSchema.xsd
注意
您需要手动为 Color
类添加包级 XmlAdapter
才能正确执行 XML 转换。
处理有问题的类
当您有一个 JAXB 默认情况下无法转换的类时,您可以使用 XmlAdapter
将其转换为可以用于编码和解码的类。
关于java - 如何在 JAXB 中存储对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25150305/