有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何用Java为带有属性的自包含标记编写xml注释

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

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

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


共 (1) 个答案

  1. # 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 IMPL倾向于这样做(请参见: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"/>