LINQ to XML Newbie Question
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">
<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.Descend开发者_运维百科ants("worksheet").Elements("sheetData")
select row;
But it always returns an empty set.
What am I missing?
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;
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.
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.
Here is some code I wrote in Linqpad that does the filter on c where t = s.
I know the answer has been accepted, but this solution actually does the filtering whereas none of the other answers above do :)
Hope this helps!
void Main()
{
var xml = @"<?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"">
<sheetData>
<row r=""1"" spans=""1:2"">
<c r=""A1"" t=""s"">
<v>0</v>
</c>
<c r=""A2"" t=""b"">
<v>0</v>
</c>
<c r=""B1"" t=""s"">
<v>1</v>
</c>
</row>
</sheetData>
</worksheet>";
XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var d = XDocument.Parse(xml);
//d.Dump();
//d.Dump("xdocument dump");
var q = from cell in d.Root.Descendants(ns + "sheetData").Descendants(ns + "row").Descendants(ns + "c")
where cell.Attributes("t").FirstOrDefault().Value == "s"
select cell;
q.ToList().Dump();
}
精彩评论