标签:linq-to-xml linq xml c net
我在这个网站上还很新,这是我的第一个问题.我阅读了文档,但是如果您违反任何行为准则,对不起.
这是我的问题:
我在流中有一个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>)键,但是我只得到值Name,Type为空(我检查数据是否不存在(即== null),将其替换为“”).
当我添加Key =(List< string>)键时,系统会引发“ 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
};
有谁知道如何查询我的文件以填充我的班级?
提前致谢!
解决方法:
您的键不是字符串,而是XElements,您无法将其转换为字符串.根据您想要获得什么,您可以执行以下操作:
Key = (List<string>)keys.Select(x=>x.Value).ToList()
要么
Key = (List<string>)keys.Select(x=>x.ToString()).ToList()
但是您在xml上什么都不会得到,因为您查询的不是产品,而是查询的YourKey,获取产品的第一行更改为:
var list = from product in productName.Descendants("Product_Key")
如果要获取类型,则应考虑拥有多个Type pro产品.您可以将列表中的类型作为键查询,或者可以确保它们都相同,因此可以只选择第一个:
var list = from product in productName.Descendants("Product_Key")
let name = product.Attribute("Name")
let keys = product.Elements("Key")
select new MsProduct
{
Name = (string)name,
Type = keys.First().Attribute("Type").Value,
Key = (List<string>)keys.Select(x=>x.Value).ToList()
};
标签:linq-to-xml,linq,xml,c,net 来源: https://codeday.me/bug/20191026/1935406.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。