gpt4 book ai didi

java - 如何在 Java 中为具有属性的自包含标记编写 xml 注释

转载 作者:行者123 更新时间:2023-11-30 09:12:17 25 4
gpt4 key购买 nike

我正在使用包 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();

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

最佳答案

您可以执行以下操作:

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 注释用于指定 namespace 限定。不能保证使用 @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"/>

关于java - 如何在 Java 中为具有属性的自包含标记编写 xml 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21674070/

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