2011-06-07 42 views
2

這是我想讀取XML的一個樣本:如何使用LINQ to XML來檢索嵌套數組?

<?xml version="1.0" encoding="UTF-8"?> 
<hash> 
    <result> 
    <properties type="array"> 
     <property> 
     <registers type="array"> 
      <register> 
      <dials type="integer">6</dials> 
      </register> 
      <register> 
      <dials type="integer">6</dials> 
      </register> 
     </registers> 
     <unit-balance type="integer">-104</unit-balance> 
     </property> 
    </properties> 
    <account-number>90</account-number> 
    </result> 
    <version>1.0</version> 
</hash> 

我可以閱讀下面的代碼的第一級,但如何讓寄存器,並將它們與相應的屬性相關聯?

var rawProperties = from property in customerXml.Descendants("property") 
        select new 
        { 
         UnitBalance = property.Element("unit-balance").Value 
        }; 

回答

3

事情是這樣的:

var rawProperties = customerXml.Descendants("property") 
    .Select(arg => 
     new 
     { 
      UnitBalance = arg.Element("unit-balance").Value, 
      Registers = arg.Descendants("dials").Select(x => x.Value).ToList() 
     }) 
    .ToList();