java - 如何在 JAXB 中存储对象?

标签 java jaxb

我有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/

相关文章:

java - 如何向spring webflow controller发送请求参数

java - 需要使用自己的属性之一重命名 XML 元素

java - 解码时发生错误

java - 如何在 Jaxb 编写的 XML 中添加 &lt;![CDATA[ 和 ]]>

java - 尽管设置为超过两分钟,但套接字在两分钟后超时

java - 我将使用什么语法让我的程序忽略下划线、标点符号和所有其他驼峰式命名法等

java - jaxb 解码列表不起作用

java - 如何处理带有 MixedContent 数据的 JAXB ComplexType?

java - 如何实现以不同对象作为值的 Java Hashmap

java - 如何在具有多个类的数组中转换对象?