nyxz
nyxz

Reputation: 7418

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"/>
 <names rdf:ID="Washington"/>
 <names rdf:ID="Sofia"/>
 <names rdf:ID="Miami"/>
</rdf:RDF>

Upvotes: 2

Views: 2749

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160852

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

Upvotes: 2

Related Questions