如何解决如何从此xml文档中提取数据
我想从每个行星和小行星中提取数据(在本例中不是)并将其放在字符串列表中。 因此,一个行星列表将包含(按顺序):
- 名称
- x位置
- 位置y
- 半径
- 速度x
- 速度y (任何)-邻居
遍历xml时遇到很多麻烦,并且此imo上没有很多好的教程。
xml:
<galaxy>
<planet>
<name>Kobol</name>
<position>
<x>45</x>
<y>310</y>
<radius>7</radius>
</position>
<speed>
<x>0.3</x>
<y>-0.6</y>
</speed>
<neighbours>
<planet>Unicron</planet>
<planet>Koarth</planet>
</neighbours>
<color>blue</color>
<oncollision>blink</oncollision>
</planet>
<planet>
<name>Namek</name>
<position>
<x>60</x>
<y>102</y>
<radius>15</radius>
</position>
<speed>
<x>0.1</x>
<y>0.2</y>
</speed>
<neighbours>
<planet>Helicon</planet>
<planet>Synnax</planet>
<planet>Xenex</planet>
<planet>Alderaan</planet>
</neighbours>
<color>orange</color>
<oncollision>blink</oncollision>
</planet>
</galaxy>
有人可以帮忙吗?
解决方法
您正在谈论的是XML 反序列化。另一种方法(对象到xml)称为序列化
通常在StackOverflow和Web上都有很多这两个示例。使用这些术语进行搜索将对您有所帮助。
这是StackOverflow中的一个好东西:
How to Deserialize XML document
,我们可以通过以下方式定义表示Xml的模型:
[XmlRoot("galaxy")]
public class Galaxy
{
[XmlElement("planet")]
public List<Planet> Planets { get; set; }
}
public class Planet
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("position")]
public Position Position { get; set; }
[XmlElement("speed")]
public Speed Speed { get; set; }
[XmlElement("neighbours")]
public List<Neighbour> Neighbours { get; set; }
[XmlElement("color")]
public string Color { get; set; }
[XmlElement("oncollision")]
public string OnCollision { get; set; }
}
public class Position
{
[XmlElement("x")]
public double X { get; set; }
[XmlElement("y")]
public double Y { get; set; }
[XmlElement("radius")]
public double Radius { get; set; }
}
public class Speed
{
[XmlElement("x")]
public double X { get; set; }
[XmlElement("y")]
public double Y { get; set; }
}
public class Neighbour
{
[XmlElement("planet")]
public string Name { get; set; }
}
请注意我们如何使用属性定义Xml的布局,并将其映射回对象。
有了这个,我们可以通过以下方式反序列化Xml:
XmlSerializer serializer = new XmlSerializer(typeof(Galaxy));
using (FileStream stream = new FileStream(filePath,FileMode.Open))
{
Galaxy galaxy = (Galaxy) serializer.Deserialize(stream);
foreach (Planet planet in galaxy.Planets)
{
Console.WriteLine(planet.Name);
}
}
输出
Kobol
Namek
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。