如何在 Java 中使用 XPath 访问 OWL 文档? [英] How to access OWL documents using XPath in Java?
问题描述
我有一个 XML 文件形式的 OWL 文档.我想从这个文档中提取元素.我的代码适用于简单的 XML 文档,但不适用于 OWL XML 文档.
I am having an OWL document in the form of an XML file. I want to extract elements from this document. My code works for simple XML documents, but it does not work with OWL XML documents.
我实际上是想得到这个元素:/rdf:RDF/owl:Ontology/rdfs:label
,为此我做了这个:
I was actually looking to get this element: /rdf:RDF/owl:Ontology/rdfs:label
, for which I did this:
DocumentBuilder builder = builderfactory.newDocumentBuilder();
Document xmlDocument = builder.parse(
new File(XpathMain.class.getResource("person.xml").getFile()));
XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression xPathExpression = xPath.compile("/rdf:RDF/owl:Ontology/rdfs:label/text()");
String nameOfTheBook = xPathExpression.evaluate(xmlDocument,XPathConstants.STRING).toString();
我也尝试以这种方式仅提取 rdfs:label
元素:
I also tried extracting only the rdfs:label
element this way:
XPathExpression xPathExpression = xPath.compile("//rdfs:label");
NodeList nodes = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);
但是这个节点列表是空的.
But this nodelist is empty.
请让我知道我哪里出错了.我正在使用 Java XPath API.
Please let me know where I am going wrong. I am using Java XPath API.
推荐答案
因为 xpath 不知道您正在使用的命名空间.尝试使用:
as xpath does not know the namespaces you are using. try using:
"/*[local-name()='RDF']/*[local-name()='Ontology']/*[local-name()='label']/text()"
本地名称将忽略命名空间并起作用(对于它找到的第一个实例)
local name will ignore the namespaces and will work (for the first instance of this that it finds)
这篇关于如何在 Java 中使用 XPath 访问 OWL 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!