views:

101

answers:

3

I have an loaded an XML document with the following structure:

<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"&gt;
  <sheetData>
    <row r="1" spans="1:2">
      <c r="A1" t="s">
        <v>0</v>
      </c>
      <c r="B1" t="s">
        <v>1</v>
      </c>
    </row>
  </sheetData>
</worksheet>

I want to query the document for any elements named c that has the attribute t = s.

I have tried many different variations on how to do this:

XDocument xmlDoc = XDocument.Load(@"..\..\Sheet1.xml");
var rows = from row in xmlDoc.Root.Descendants("worksheet").Elements("sheetData")
       select row;

But it always returns an empty set.

What am I missing?

+1  A: 

The Root element is the <worksheet/> element so asking the root for a worksheet descendant will always return an empty set. Remove the .Descendants("worksheet") clause and you should start seeing some results.

James Keesey
That didn't work. I tried:xmlDoc.Elements("row")
coson
What about `xmlDoc.Root.Elements("sheetData").Elements("row)`?
James Keesey
I tried that earlier and it didn't work for me either. I don't know if this has anything to do with it, but the snippet is from a Microsoft Excel spreadsheet converted to XML.
coson
+3  A: 

You need to specify the namespace of the node you are getting with Descendants or Elements.

XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var rows = from row in xmlDoc.Root.Descendants(ns + "sheetData")
       select row;
brianary
this caught me out the first time I used Linq to XML.
Sekhat
A: 
XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
XDocument xmlDoc = XDocument.Load(@"..\..\Sheet1.xml");
var rows = from row in xmlDoc.Root.Element(ns + "sheetData").Elements(ns + "row")
       select row;

This grabs all the "row" elements from within the root/sheetData element.

DanM