简体   繁体   中英

Adding Sub Children to RDF using Jena

Okay I've got a problem I'd appreciate someone spreading some light on. Basically I have the following example below

<rdf:Description rdf:about="http://test.com">
<hasX></hasX>
<hasY></hasY>
<hasA></hasA>
<hasA></hasA>
<hasA></hasA>
</rdf:Description>

I'm trying to produce the following:

<rdf:Description rdf:about="http://test.com">
<hasX></hasX>
<hasY></hasY>
<hasZ>
<hasA></hasA>
<hasA></hasA>
<hasA></hasA>
</hasZ>
</rdf:Description>

I've tried adding Property to a Property then a Resource, declaring new Resource, adding Literals, every possible combination of these, however the close I've gotten is it to generate a new rdf:description block containing the data I want, outside of the original rdf:description making it worthless.

I really don't want another <rdf:Description rdf:about=""> to describe the A tags.

Here's a small test example

String NS = "http://example.com/test";      
Model m = ModelFactory.createDefaultModel();
Resource r = m.createResource("http://meetup/nyc");

Property p = m.createProperty(XmlParser.NS + "hasData");
Property p2 = m.createProperty(XmlParser.NS + "hasData");
Property p3 = m.createProperty(XmlParser.NS + "hasData");

r.addProperty(p, "somedata");
r.addProperty(p2, "somedata2");
r.addProperty(p3, "somedata3");

m.write(System.out);

Creating a Resource from a model doesn't automatically add it to that model. I generally add triples to a model via one of the add methods of the Model class:

    String NS = "http://example.com/test#";
    Model m = ModelFactory.createDefaultModel();
    Resource r = m.createResource("http://meetup/nyc");

    Property p = m.createProperty(NS + "hasData");

    m.add(r, p, "somedata");
    m.add(r, p, "more data");

    m.write(System.out);

This will create:

<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
           xmlns:j.0="http://example.com/test#" > 
     <rdf:Description rdf:about="http://meetup/nyc">
         <j.0:hasData>more data</j.0:hasData>
         <j.0:hasData>somedata</j.0:hasData>
      </rdf:Description>
   </rdf:RDF>

As the other responders have said, don't think in terms of the XML tree structure. However, if seeing your graph in an XML tree is helpful to your understanding of the model, change the output syntax to the compact RDF/XML form:

m.write( System.out, "RDF/XML-ABBREV" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM