gpt4 book ai didi

java - 向从模式生成的 JAXB 类添加额外的方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:13 24 4
gpt4 key购买 nike

这是我的 XSD 文件的一个简单摘录

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

<element name="document">
<attribute name="title" use="required"/>
</element>
</schema>

我使用 maven-jaxb2-plugin 从中生成 Java 类。 Document 类有一个 getTitle() 方法来返回 title 属性的文本。

我想向 Document 添加一个额外的方法:

public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}

我希望我的额外方法出现在解码对象上(而不是我只是调用它或编写包装类),因为我想将顶级解码对象传递给字符串模板并让它迭代子-调用我的额外方法的元素。

我找到了 instructions但他们告诉我在 Unmarshaller 上设置一个属性,而我的(Mac OS X、Java 7)实现似乎不支持任何属性。

我应该怎么做?

最佳答案

按照 Brian Henry 提供的链接,我发现我可以在我的架构文件中内联执行绑定(bind)自定义来执行我想要的操作。效果与 Brian 的解决方案完全相同,但它不需要引用对 com.sun.xml.internal 的引用。

首先,对模式文件进行了一些修改:

<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="ns"
xmlns:tns="sns" elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">

<element name="document">
<annotation>
<appinfo>
<jaxb:class implClass="DocumentEx" />
</appinfo>
</annotation>
<attribute name="title" use="required"/>
</element>
</schema>

当架构被编译成 Java 代码时,生成的 ObjectFactory 将引用 DocumentEx 而不是 DocumentDocumentEx 是我创建的一个类,它看起来像这样:

public class DocumentEx extends Document {
public String getStrippedTitle() {
return getTitle().replaceAll("\\s+", "");
}
}

Document(我正在扩展的类)仍然由 schema-to-Java 编译器生成。现在,当我解码文档时,我实际上得到了一个 DocumentEx 对象:

    JAXBContext jaxbContext = JAXBContext.newInstance("com.example.xml");
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(testSchema);
DocumentEx doc = (DocumentEx)unmarshaller.unmarshal(xmlFile);

Oracle 上有一些(难以解析的)文档和一些有用的例子在 O'Reilly .

关于java - 向从模式生成的 JAXB 类添加额外的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14285928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com