2009-12-21 62 views
0

我有一個加載XML文檔結構如下:的LINQ to 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="B1" t="s"> 
     <v>1</v> 
     </c> 
    </row> 
    </sheetData> 
</worksheet> 

我想查詢名爲c具有屬性t = s的任何元素的文檔。

我試圖就如何做到這一點許多不同的變化:

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

但它總是返回一個空集。

我錯過了什麼?

回答

1

根元素是<worksheet/>元素,以便詢問根爲工作表後代將始終返回一個空集。刪除.Descendants("worksheet")條款,你應該開始看到一些結果。

+0

這沒有奏效。我嘗試過: xmlDoc.Elements(「row」) – coson

+0

'xmlDoc.Root.Elements(「sheetData」)。Elements(「row」)? –

+0

我以前試過,它對我也不適用。我不知道這有什麼關係呢,但片段是從Microsoft Excel電子表格轉換爲XML。 – coson

3

你需要指定要與後代或元素得到節點的命名空間。

XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; 
var rows = from row in xmlDoc.Root.Descendants(ns + "sheetData") 
     select row; 
+0

這抓住了我了我第一次使用的LINQ to XML。 – Sekhat

0
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; 

這抓住所有的 「行」 的元件從根/ sheetData元件內。

0

下面是一些代碼我在Linqpad,做第C其中t = S濾波器寫道。

我知道答案已被接受,但這種解決方案實際上做的過濾,而沒有其他的答案上面做:)

希望這有助於中!

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(); 

}