如何提取同级别的所有节点

时间:2014-11-29 13:28:51

标签: c# xml linq linq-to-xml xelement

我正在尝试获取所有文件夹标题属性,并希望存储在列表中

以下是我的XML文件

<?xml version="1.0" encoding="utf-16" ?>
<Folders Name="MyFolderName">
  <Folder Caption="Bank">
    <Card Caption="BankName1">
      <Property Type="String" Caption="Bank">Bank1</Property>
    </Card>
    <Card Caption="BankName2">
      <Property Type="String" Caption="Bank">Bank2</Property>
    </Card>
  </Folder>
  <Folder Caption="Bills">
    <Card Caption="BillName1">
      <Property Type="Numeric" Caption="BillName">BillName1Data</Property>
    </Card>
    <Card Caption="BillName2">
      <Property Type="Numeric" Caption="BillName1">BillName2Data</Property>
    </Card>
  </Folder>
</Folders>

下面是我的查询

public static List<Folder> ExtractFolders()
    {
        XDocument doc = XDocument.Load(@"I:\WindowsPhone\xmlTesting\xmlTesting\Data\VaultData.xml");
        List<Folder> folders = (from c in doc.Descendants("Folders")
                                select new Folder()
                                {
                                    Caption = c.Element("Folder").Attribute("Caption").Value
                                }).ToList<Folder>();
        return folders;
    }

我只获得第一个文件夹

我怎样才能获得文件夹列表

1 个答案:

答案 0 :(得分:1)

更改

    List<Folder> folders = (from c in doc.Descendants("Folders")
                            select new Folder()
                            {
                                Caption = c.Element("Folder").Attribute("Caption").Value
                            }).ToList<Folder>();

    List<Folder> folders = (from c in doc.Descendants("Folder")
                            select new Folder()
                            {
                                Caption = c.Attribute("Caption").Value
                            }).ToList<Folder>();
相关问题