使用 Linq C# 的 XML 中的所有节点
本文关键字:节点 XML Linq 使用 | 更新日期: 2023-09-27 18:33:56
可能的重复项:
使用 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 个小时在谷歌上搜索这个,但还没有找到任何东西。
预期产出
将信息保存在类对象(类型和状态(中。
我想读取客户标签,以便我可以知道该人是否已经是客户
任何帮助将不胜感激。
谢谢
更新
根据从拉斐尔·阿尔特豪斯收到的投入
我有以下代码:
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,
}
我可以在一个查询中同时执行这两个操作吗?还是这种方法对性能没有那么重,所以我可以使用这个?
类似的东西?
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();
}