gpt4 book ai didi

c# - 使用 Linq 查询解析 List 中的 XML

转载 作者:数据小太阳 更新时间:2023-10-29 02:29:18 25 4
gpt4 key购买 nike

我的问题是如何实现从 XML 文件解析为 List 类的 linq 查询这是自定义类:

CustomClass.cs

public class ListItem
{
public int id;
public string name;
public int minLevel;
public int minAttr1;
public int minAttr2;
public float damage;
public float additionalDmg;
public string additionalDmgType;
public float range;
public float cost;

public ListItem(
int _id,
string _name,
int _minLevel,
int _minAttr1,
int _minAttr2,
float _damage,
float _additionalDmg,
string _additionalDmgType,
float _range,
float _cost)
{
id = _id;
name = _name;
minLevel = _minLevel;
minAttr1 = _minAttr1;
minAttr2 = _minAttr2;
damage = _damage;
additionalDmg = _additionalDmg;
additionalDmgType = _additionalDmgType;
range = _range;
cost = _cost;
}
}

这是我拥有的 xml 文件的示例:

文件.xml

<?xml version="1.0" encoding="utf-8"?>
<Weapons>
<Weapon id="0">
<Name>spada</Name>
<MinLevel>1</MinLevel>
<MinAttr1>10</MinAttr1>
<MinAttr2>5</MinAttr2>
<Damage>100</Damage>
<AdditionalDmg>10</AdditionalDmg>
<AdditionalDmgType>Electric</AdditionalDmgType>
<Range>1</Range>
<Cost>1000</Cost>
</Weapon>
<Weapon id="1">
<Name>spada2</Name>
<MinLevel>1</MinLevel>
<MinAttr1>10</MinAttr1>
<MinAttr2>5</MinAttr2>
<Damage>100</Damage>
<AdditionalDmg>10</AdditionalDmg>
<AdditionalDmgType>Electric</AdditionalDmgType>
<Range>1</Range>
<Cost>1000</Cost>
</Weapon>
</Weapons>

这是需要 linq 查询进行解析的 Importer 类:

Importer.cs

class Importer
{
public void ImportXML()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
XDocument xml = XDocument.Load(sr);
sr.Close();

//Miss here linq query
}
}
}
}

我的尝试(但“数据”变量仍然为空):

 var data = from item in xml.Elements("weapon")
select new
{
name = item.Element("Name").Value,
minLevel = item.Element("MinLevel").Value
};
foreach (var p in data)
Debug.WriteLine(p.ToString());

最佳答案

四个问题:

  1. <Weapon>元素是 <Weapons> 的子元素根元素不是整个文档。

  2. XML 区分大小写,因此在按名称搜索元素或属性时,您需要完全匹配大小写。因此 xml.Root.Elements("weapon")应该是 xml.Root.Elements("Weapon") .

  3. 转换 XElement 时不同类型的值,比如 int , 你应该使用 explicit casting .这样可以正确处理国际化。对 XAttribute 做同样的事情转化。

  4. “id”是一个属性,所以使用 XElement.Attribute() 访问它。

因此:

        var data = from item in xml.Root.Elements("Weapon")
select new
{
name = (string)item.Element("Name"),
minLevel = (int)item.Element("MinLevel"),
id = (int)item.Attribute("id")
};

关于c# - 使用 Linq 查询解析 List<CustomClass> 中的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278518/

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