您可以xml:base
通过获取适当的 RDFWriter 并将其xmlbase
属性设置为您选择的xmlbase
. 下面的代码从一个字符串中读取一个模型(这个问题的重要部分是关于如何编写模型,而不是它来自哪里),然后用 RDF/XML 将其写入两次,每次使用不同的xml:base
.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFWriter;
public class ChangeBase {
public static void main(String[] args) throws IOException {
final String NS = "http://example.org/";
final String text = "" +
"@prefix ex: <"+NS+">.\n" +
"ex:foo a ex:Foo .\n" +
"ex:foo ex:frob ex:bar.\n";
final Model model = ModelFactory.createDefaultModel();
try ( final InputStream in = new ByteArrayInputStream( text.getBytes() )) {
model.read( in, null, "TTL" );
}
// get a writer for RDF/XML-ABBREV, set its xmlbase to the NS, and write the model
RDFWriter writer = model.getWriter( "RDF/XML-ABBREV" );
writer.setProperty( "xmlbase", NS );
writer.write( model, System.out, null );
// change the base to example.com (.com, not .org) and write again
writer.setProperty( "xmlbase", "http://example.com" );
writer.write( model, System.out, null );
}
}
输出是(请注意,在第一种情况下,基数是htttp://example.org/
,而在第二种情况下,它是http://example.com
(区别是 .org 与 .com):
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:ex="http://example.org/"
xml:base="http://example.org/">
<ex:Foo rdf:about="foo">
<ex:frob rdf:resource="bar"/>
</ex:Foo>
</rdf:RDF>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:ex="http://example.org/"
xml:base="http://example.com">
<ex:Foo rdf:about="http://example.org/foo">
<ex:frob rdf:resource="http://example.org/bar"/>
</ex:Foo>
</rdf:RDF>