2011-11-28 33 views
1

需要幫助解析以下XML。我是Linq to XML的新手。 我想分析在一個單一的對象數組中的所有圖像數據,我似乎沒有找到一種方法,如何根據元素或屬性創建對象

這裏是一個示例XML,

<Object type="System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="Form1" children="Controls"> 
    <Object type="System.Windows.Forms.PictureBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="PictureBox1" children="Controls"> 
     <Property name="TabIndex">0</Property> 
     <Property name="Size">206, 152</Property> 
     <Property name="ImageLocation">C:\Documents and Settings\Administrator\Desktop\logo2w.png</Property> 
     <Property name="Location">41, 68</Property> 
     <Property name="TabStop">False</Property> 
     <Property name="Name">PictureBox1</Property> 
     <Property name="DataBindings"> 
      <Property name="DefaultDataSourceUpdateMode">OnValidation</Property> 
     </Property> 
    </Object> 
    <Object type="System.Windows.Forms.PictureBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="PictureBox2" children="Controls"> 
     <Property name="TabIndex">0</Property> 
     <Property name="Size">206, 152</Property> 
     <Property name="ImageLocation">C:\Documents and Settings\Administrator\Desktop\logo2w.png</Property> 
     <Property name="Location">42, 68</Property> 
     <Property name="TabStop">False</Property> 
     <Property name="Name">PictureBox2</Property> 
     <Property name="DataBindings"> 
      <Property name="DefaultDataSourceUpdateMode">OnValidation</Property> 
     </Property> 
    </Object>  
</Object> 

我要訪問的價值PictureObjects[0].Location = 41, 68PictureObjects[1].Location = 42, 68我可以做嗎?

我看到了幾個樣本,我可以根據節點名稱創建這樣的對象,而不是基於節點屬性值? C# LINQ with XML, cannot extract multiple fields with same name into object

有人可以指導或讓我知道它是否可行?

回答

1

你可以用這個啓動,下面的代碼只需選擇的TabIndex和Size屬性,顯然增加其他不會是一個棘手:

XDocument xdoc = XDocument.Load(@"path to a file or use text reader"); 
var tree = xdoc.Descendants("Object").Skip(1).Select(d => 
      new 
      { 
       Type = d.Attribute("type").Value, 
       Properties = d.Descendants("Property") 
      }).ToList(); 

var props = tree.Select(e => 
    new 
    { 
     Type = e.Type, 
     TabIndex = e.Properties 
        .FirstOrDefault(p => p.Attribute("name").Value == "TabIndex") 
        .Value, 
     Size = e.Properties 
       .FirstOrDefault(p => p.Attribute("name").Value == "Size") 
       .Value 
    }); 
+0

謝謝!我馬上試試它! :) – user1069342

+0

再次感謝您!像魅力一樣工作! – user1069342

+0

如果您認爲特定的答案完全覆蓋了您的問題,您可以通過標記爲已接受的答案來接受它,或者等待幾天以查看是否有更好的答案進來,那麼您可以將賞金(獎金)以歡迎更多的人來幫助您。這是一個StackOverflow問題/回答生命週期 – sll

相關問題