我在这个网站上还比较新,这是我的第一个问题。我已经阅读了文档,但如果我违反任何行为准则,请提前道歉。
这是我的问题:
我有一个XML文件流。我的目标是获取属性“名称”,“类型”以及关键字(由于明显的原因已更改)。
<YourKey>
<Product_Key Name="eMbedded Visual C++ 4.0">
<Key ID="5" Type="Static Activation Key" ClaimedDate="">BBBBB-QW36D-DPT6T-BBBB-ZZZZZ</Key>
</Product_Key>
<Product_Key Name="Windows 10 Home">
<Key ID="1251" Type="Retail" ClaimedDate="1/25/2017">ZZZZZ-6GBG7-ZZZZZ-8JG23-FM47H</Key>
<Key ID="1251" Type="Retail" ClaimedDate="8/23/2016">FEFEF-FVD7K-EEEEF-BEBEB-VMHX7</Key>
<Key ID="1251" Type="Retail" ClaimedDate="4/28/2016">EEZZE-GYB6P-ZZZEE-R72PQ-EEEEZ</Key>
</Product_Key>
</YourKey>
我创建了一个类来保存数据。
public class MsProduct
{
public string Name { get; set; }
public string Type { get; set; }
public List<string> key { get; set; }
}
我创建了一个 MsProduct
列表,将 var list
(见下文)的每个元素添加到我的对象中。
我创建了一个 Linq 查询,如果没有 Key = (List<string>)keys
,它可以编译通过,但我只得到 Name, Type
值为空(如果数据不存在就替换为空格)。
当我添加 Key = (List<string>)keys
时,系统会抛出 "System.InvalidCastException"。
以下是我的查询:
var productName = XDocument.Load(fileXml);
var list = from product in productName.Descendants("YourKey")
let name = product.Attribute("Name")
let type = product.Attribute("Type")
let keys = product.Elements("Key")
select new MsProduct
{
Name = (string)name,
Type = (string)type,
Key = (List<string>)keys
};
有人知道如何查询我的文件并填充我的类吗?
提前致谢!