Вопрос

I'm using the annotations from the package javax.xml.bind.annotation to construct SKOS XML files. I have some trouble about the best way to realize lines like the following (please, observe that the rdf prefix has been set in the package-info.java file):

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

Currently, I do it by defining a class and by adding a property to the class, e.g.

@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";              
}

and then I create a field in the class that I'm going to serialize, e.g.

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

Is this the only way or I can save time by using a more compact approach?

Это было полезно?

Решение

You could do the following:

Java Model

Type

JAXB derives default names from classes and packages, so you only need to specify a name if it difers from the default. Also you should not include the prefix as part of the name,

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";

}

package-info

The @XmlSchema annotation is used to specify the namespace qualification. The use of @XmlNs to specify the prefix is not guaranteed to result in that prefix being used in the marshalled XML, but JAXB impls tend to do this (see: 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.*;

Demo Code

Demo

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);
    }

}

Output

<?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"/>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top