Java/RDF&Jena

RDF - Eclipse Apache Jena Xml 파일 읽어오기

기은P 2020. 3. 10. 14:58
반응형

 

Apache Jena를 사용하여 RDF형식으로 작성된 XML파일을 읽는 코드다

Jena Model Reading 기능이다.

 

public static final String xmlPath로 파일 경로를 지정해준다.

"file:"이 들어가야 하는 점 유의할 것.


Model model = ModelFactory.createDefaultModel(); 

기본 모델 객체를 선언하고,

model.read()를 통해 xml 파일을 읽는다.

 

package org.rcp_dbview.util;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

public class JenaConfig {
	// RDF/XML문서의 파일 경로
	public static final String xmlPath = "C:\\workplace\\Source\\RCP_DBView\\temp\\130604_NL_EQ111.xml";
	
	public void Init() {
		Model model = ModelFactory.createDefaultModel();			
		FileInputStream file = new FileInputStream(new File(JenaConfig.xmlPath));
		String base2 = "http://iec.ch/TC57/2013/CIM-schema-cim16";
		model.read(file, base2); // 파일 객체로 경로를 읽는다.
        // base2는 RDF파일의 가장 상위에 있는 링크를 작성한다.
        // reading되는 근간이 되는 링크를 base로 삼는 것임.

		// Iterator를 통해서 주어/행동/목적어 별로 출력
		StmtIterator iter = model.listStatements();
		while (iter.hasNext()) {
			Statement stmt = iter.nextStatement(); // get next statement
			Resource subject = stmt.getSubject(); // get the subject
			Property predicate = stmt.getPredicate(); // get the predicate
			RDFNode object = stmt.getObject(); // get the object

			System.out.print(subject.toString());
			System.out.print(" " + predicate.toString() + " ");
			if (object instanceof Resource) {
				System.out.print(object.toString());
			} else {
				// object is a literal
				System.out.print(" \"" + object.toString() + "\"");
			}

			System.out.println(" .");
		}
		
	}
}

 

이전 글에 사용법에 대해 작성하였는데,

Reading 기능이 빠져있는 것 같아 추가했다.

반응형