如何使用 LINQ 解析 OWL 文件(包含 RDF 命名空间)
我设法使用 LINQ 解析一个简单的 XML 文件并将其写入列表框,但是当我尝试从 OWL 文件获取值时,我没有通过查询获得任何结果,因此“变量”为空。这是我的尝试之一:
XDocument owlXML = XDocument.Load(Server.MapPath("App_Data\\filename.owl"));
var variables = from variable in owlXML.Descendants("names")
where variable.Attribute("rdf:ID") != null
select new
{
type = tog.Attribute("rdf:ID").Value
};
ListBox1.DataSource = clothes;
ListBox1.DataBind();
OWL 文件
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...
...
xml:base="http://www.owl-ontologies.com/Ontology1299428518.owl">
<owl:Ontology rdf:about=""/>
<owl:Class rdf:ID="animal"/>
<owl:Class rdf:ID="natural_disaster">
<rdfs:subClassOf>
<owl:Class rdf:ID="disaster"/>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Class rdf:ID="natural_phenomenon"/>
</rdfs:subClassOf>
</owl:Class>
<names rdf:ID="New York"/>
<names rdf:ID="Washington"/>
<names rdf:ID="Sofia"/>
<names rdf:ID="Miami"/>
</rdf:RDF>
I managed to parse a simple XML file using LINQ and write it to a list box, but when I tried to get the values from the OWL file I didn't get any result by the query, so the "variables" is empty. Here is one of my attempts to do it:
XDocument owlXML = XDocument.Load(Server.MapPath("App_Data\\filename.owl"));
var variables = from variable in owlXML.Descendants("names")
where variable.Attribute("rdf:ID") != null
select new
{
type = tog.Attribute("rdf:ID").Value
};
ListBox1.DataSource = clothes;
ListBox1.DataBind();
The OWL File
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...
...
xml:base="http://www.owl-ontologies.com/Ontology1299428518.owl">
<owl:Ontology rdf:about=""/>
<owl:Class rdf:ID="animal"/>
<owl:Class rdf:ID="natural_disaster">
<rdfs:subClassOf>
<owl:Class rdf:ID="disaster"/>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Class rdf:ID="natural_phenomenon"/>
</rdfs:subClassOf>
</owl:Class>
<names rdf:ID="New York"/>
<names rdf:ID="Washington"/>
<names rdf:ID="Sofia"/>
<names rdf:ID="Miami"/>
</rdf:RDF>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用适当的命名空间,
rdf
不是属性名称的一部分,它是它所包含的命名空间 - 您必须声明并使用命名空间 - 对于 Linq to XML 这意味着使用 < a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.aspx" rel="nofollow">XNamespace
- 这个有效:确保代码中的命名空间值与 XML 中的声明方式完全匹配。
另外,由于您只有一个感兴趣的值,因此不必在此处使用匿名类型,因此您可以通过直接返回字符串来简化(
types
则为IEnumerable< /代码>):
You have to use the appropriate namespace,
rdf
is not part of the attribute name, it is the namespace it is contained in - you have to declare and use the namespace - for Linq to XML that means usingXNamespace
- this works:Make sure that the value of the namespace in your code matches exactly how it is declared in the XML.
Also since you only have one value you are interested in you do not have to use an anonymous type here, you can simplify by returning a string directly (
types
then would beIEnumerable<string>
):