【问题标题】:How to write an xml annotation in Java for a self-contained tag with attributes如何在 Java 中为具有属性的自包含标签编写 xml 注释
【发布时间】:2014-02-10 10:03:00
【问题描述】:

我正在使用包javax.xml.bind.annotation 中的注释来构造SKOS XML 文件。我对实现以下行的最佳方法有些麻烦(请注意package-info.java 文件中已设置rdf 前缀):

<rdf:type rdf:resource="http://www.w3.org/2004/02/skos/core#ConceptScheme" />

目前,我通过定义一个类并向该类添加一个属性来做到这一点,例如

@XmlRootElement(name = "type")
@XmlAccessorType(XmlAccessType.FIELD)
class Type{
  @XmlAttribute(name="rdf:resource")
  protected final String res="http://www.w3.org/2004/02/skos/core#ConceptScheme";              
}

然后我在要序列化的类中创建一个字段,例如

@XmlElement(name="type")
private Type type = new Type();

这是唯一的方法还是我可以通过使用更紧凑的方法来节省时间?

【问题讨论】:

  • 我不太明白你在问什么。你能提供一些额外的细节吗?
  • 首先,让我感谢您的关注。请忽略“目前,我这样做......”中的所有内容。问题是:如何通过 JAXB 以非常紧凑的方式编写条目 &lt;rdf:type rdf:resource="http://www.w3.org/2004/02/skos/core#ConceptScheme" /&gt;?

标签: java xml jaxb xml-binding


【解决方案1】:

您可以执行以下操作:

Java 模型

类型

JAXB 从类和包派生默认名称,因此如果名称与默认名称不同,您只需指定一个名称。此外,您不应将前缀作为名称的一部分,

package forum21674070;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Type {

      @XmlAttribute
      protected final String res="http://www.w3.org/2004/02/skos/core#ConceptScheme";

}

包裹信息

@XmlSchema 注解用于指定命名空间限定。使用@XmlNs 指定前缀并不能保证在编组的 XML 中使用该前缀,但 JAXB impls 倾向于这样做(请参阅:http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html)。

@XmlSchema(
        namespace="http://www.w3.org/2004/02/skos/core#ConceptScheme",
        elementFormDefault = XmlNsForm.QUALIFIED,
        attributeFormDefault = XmlNsForm.QUALIFIED,
        xmlns={
                @XmlNs(prefix="rdf", namespaceURI="http://www.w3.org/2004/02/skos/core#ConceptScheme")
        }
)
package forum21674070;

import javax.xml.bind.annotation.*;

演示代码

演示

package forum21674070;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Type.class);

        Type type = new Type();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(type, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8"?>
<rdf:type xmlns:rdf="http://www.w3.org/2004/02/skos/core#ConceptScheme" rdf:res="http://www.w3.org/2004/02/skos/core#ConceptScheme"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 2018-07-16
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多