开发者

How can I parse OWL file (containing RDF namespaces) with LINQ

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"/>开发者_如何学JAVA
 <names rdf:ID="Washington"/>
 <names rdf:ID="Sofia"/>
 <names rdf:ID="Miami"/>
</rdf:RDF>


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 using XNamespace - this works:

XDocument owlXML = XDocument.Load("test.xml");
XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

var variables = from variable in owlXML.Descendants("names")
                where variable.Attribute(rdf +"ID") != null
                select new
                {
                    type = variable.Attribute(rdf + "ID").Value
                };

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 be IEnumerable<string>):

var types = from variable in owlXML.Descendants("names")
            where variable.Attribute(rdf +"ID") != null
            select variable.Attribute(rdf + "ID").Value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜