0

可能重复:
使用 LINQ 从 XML 读取所有节点

我正在尝试在 C# windows 应用程序中使用 Linq 读取 XML 文件。下面给出了 xml 字符串的示例。

<Root>
<Name>John Doe</Name>
<Data>FBCCF14D504B7B2DBCB5A5BDA75BD93B</Data>
<customer>true</customer>
<Accounts>1</Accounts>
<dataSet>
     <Type1>Found matching records.</Type1>
    <Type2>No matches found.</Type2>
   <Type3>Found matching records.</Type3>
</dataSet>
</Root>

我想显示<dataset>标签内的所有数据,<datatag>我也想读取<customer>标签。

我创建了一个包含成员的类(字符串类型、字符串状态)。我想在哪里存储 type1、2 ......在状态中我想存储类型节点内的内容。

我能够做到这一点,但在代码中我必须给出

type1 = (string)row.Element("type1"), type2=(string)row.Element("type2"), 我想要一个通用代码,我不必提及每种类型。换句话说,我想读取标签的所有子节点而不提及标签名称。我花了 2 个小时在谷歌上搜索这个,但还没有找到任何东西。

预期产出

将信息保存在类对象(类型和状态)中。

我想阅读客户标签,以便知道该人是否已经是客户

任何帮助将不胜感激。

谢谢

更新

根据从 Raphaël Althaus 收到的信息

我有以下代码:

var list = xml.Descendants("dataSet").Elements()
            .Select(m => new CustomerInfo
                             {
                                 Type = m.Name.LocalName,
                                 Value = m.Value
                             }).ToList();


        foreach (CustomerInfo item in list)
        {
            MessageBox.Show(item.Type+ "   "+item.Value);

        }

为了阅读客户标签,我编写了更多代码。

var isCustomer = from customer in xmlDoc.Descendants("Root")
            select new
            {
              customer = tutorial.Element("customer").Value,
            }

我可以在一个查询中同时进行吗?或者这种方法对性能没有那么重,所以我可以使用它吗?

4

1 回答 1

1

类似的东西?

var q = xml.Descendants("dataSet").Elements()
            .Select(m => new
                             {
                                 type = m.Name.LocalName,
                                 value = m.Value
                             }).ToList();

您还可以直接填充“有成员的班级”列表

var list = xml.Descendants("dataSet").Elements()
                .Select(m => new <TheNameOfYourClass>
                                 {
                                     Type = m.Name.LocalName,
                                     Value = m.Value
                                 }).ToList();

编辑 :

要获得“客户”价值,我会做另一个查询

var customerElement = xml.Element("customer");
var isCustomer = customerElement != null && customerElement.Value == "true";

所以你可以在一个小函数中混合所有这些

public IList<YourClass> ParseCustomers(string xmlPath, out isCustomer) {
    var xml = XElement.Load(xmlPath);
    var customerElement = xml.Element("customer");
    isCustomer = customerElement != null && customerElement.Value == "true";
    return xml.Descendants("dataSet").Elements()
                    .Select(m => new <YourClass>
                                     {
                                         Type = m.Name.LocalName,
                                         Value = m.Value
                                     }).ToList();
}
于 2012-05-10T11:51:24.873 回答