gpt4 book ai didi

c# - 使用 LINQ 将具有属性的 XML 转换为对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:52 25 4
gpt4 key购买 nike

我有一个 XML 文件设置如下:

<products>
<product>
<tradegood id = "11">Textiles</tradegood>
<baseprice>3000</baseprice>
<purchaseDMs>
<mod type="A">-7</mod>
<mod type="a">-5</mod>
<mod type="i">-3</mod>
</purchaseDMs>
<resaleDMs>
<mod type="A">-6</mod>
<mod type="a">1</mod>
<mod type="R">3</mod>
</resaleDMs>
<quantity>90</quantity>
</product>

我正在使用 LINQ to XML 如下:

  XDocument productList = XDocument.Load("products.xml");

List<Product> products =
(from objProduct in productList.Element("products").Elements("product")
select new Product
{
Id = int.Parse(objProduct.Element("tradegood").Attribute("id").Value),
ProductName = objProduct.Element("tradegood").Value,
BasePrice = double.Parse(objProduct.Element("baseprice").Value),
MaxQuantity = int.Parse(objProduct.Element("quantity").Value),
PurchaseDMs = (from _mods in objProduct.Element("purchaseDMs").Elements("mod")
select new
{
key = _mods.Attribute("type").Value,
value = _mods.Value
}),
ResaleDMs = (from _mods in objProduct.Element("resaleDMs").Elements("mod")
select new
{
key = _mods.Attribute("type").Value,
value = _mods.Value
})
}).ToList;

产品类如下:

public class Product
{
private string p_ProductName;
private double p_BasePrice;
private int p_MaxQuantity;
private double p_ActualValue;
private int p_id;
private int p_Quantity;

public string ProductName
{
get { return p_ProductName; }
set { p_ProductName = value; }
}
public double BasePrice
{
get { return p_BasePrice; }
set { p_BasePrice = value; }
}
public int MaxQuantity
{
get { return p_MaxQuantity; }
set { p_MaxQuantity = value; }
}
public int QuantityAvailable
{
get { return p_Quantity; }
set { p_Quantity = value; }
}
public double ActualValue
{
get { return p_ActualValue; }
set { p_ActualValue = value; }
}
public int Id
{
get { return p_id; }
set { p_id = value; }
}

public Dictionary<string, int> ResaleDMs;
public Dictionary<string, int> PurchaseDMs;
}

我唯一不知道如何开始工作的部分是 ResaleDM 和 PurchaseDM。

select 语句均显示“无法将类型‘System.Collections.Generic.IEnumerable’隐式转换为‘System.Collections.Generic.Dictionary’。存在显式转换(您是否缺少投?)”

谁能帮我解决这个问题?我如何初始化这些字段?

最佳答案

您得到该异常的原因是因为您正在为字典属性分配 IEnumerable 投影的值。

当你这样做时:

select new 
{
key = _mods.Attribute("type").Value,
value = _mods.Value
}

您只是在创建一个具有两个属性(键和值)的新匿名对象类型。这与字典条目对象类型没有直接关联。相反,您可以使用 ToDictionary 扩展方法..

PurchaseDMs = objProduct.Element("purchaseDMs").Elements("mod")
.ToDictionary(e => e.Attribute("type").Value, e => Convert.ToInt32(e.Value)),
ResaleDMs = objProduct.Element("resaleDMs").Elements("mod")
.ToDictionary(e => e.Attribute("type").Value, e => Convert.ToInt32(e.Value))

关于c# - 使用 LINQ 将具有属性的 XML 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15037661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com