views:

55

answers:

2
<root xmlns:h="http://www.w3.org/TR/html4/"
      xmlns:f="http://www.w3schools.com/furniture"&gt;

<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

</root>

I am trying to practice LinqToXml but i can't figure out what i wanted.Simply how can i query table elements which has h or f namespace ? This was what i tried .Also i tried different ones but didn't work.

var query = from item in XDocument.Parse(xml).Elements(ns + "table")
            select item;
+4  A: 

This won't work because you're missing the root element from your query. This would work:

XNamespace ns = "http://www.w3schools.com/furniture";
var query = XDocument.Parse(xml).Element("root").Elements(ns + "table");

Now if the problem is that you want to find all "table" elements regardless of the namespace, you'd need something like this:

var query = XDocument.Parse(xml)
                     .Element("root")
                     .Elements()
                     .Where(element => element.Name.LocalName == "table");

(EDIT: As noted, you could use XDocument.Root to get to the root element if you want to. The important point is that trying to get to the table element directly from the document node itself won't work.)

Jon Skeet
I was doing XNamespace ns ="f"; but why this is wrong ? By the way i prefer root instead of Element("root").
Freshblood
@Freshblood: "f" is just the label for the namespace within the XML; the real "value" of the namespace is the URL associated with it. And yes, you could use XDocument.Root if you want to - or just call XElement.Parse instead.
Jon Skeet
+2  A: 

Namespace prefixes are not guaranteed to be a particular letter or string. The best approach would be to search by the qualified namespace.

This would get all direct child nodes of XElement xml where the namespace is uri:namespace...

var selectedByNamespace = from element in xml.Elements()
                          where element.Name.NamespaceName == "uri:namespace"
                          select element;

Another option would be to select the elements based on the fully qualified name.

var ns = "{uri:namespace}";
var selectedElements = xml.Elements(ns + "table");
Matthew Whited