我想读这样的XML。
<?xml version="1.0" encoding="utf-8" ?>
<parent>
<path>
<pathPoints>
<point>
2 0
</point>
<point>
2 1
</point>
3 1
<point>
3 2
</point>
<point>
4 2
</point>
<point>
4 4
</point>
<point>
3 4
</point>
<point>
3 5
</point>
<point>
2 5
</point>
<point>
2 7
</point>
<point>
7 7
</point>
<point>
7 5
</point>
<point>
10 5
</point>
<point>
10 2
<point>
</point>
15 2
</point>
<point>
15 6
</point>
<point>
16 6
</point>
<point>
16 7
</point>
<point>
17 7
</point>
<point>
17 10
</point>
<point>
19 10
</point>
</pathPoints>
</parent>
</path>
现在我正在尝试阅读它:
paths = (from path in doc.Descendants("path")
select new AIPath()
{
waypoints = (from i in path.Descendants("pathPoints")
{
int j = Convert.ToInt32(i.Element("point").Value),
}).ToList();
}
).ToList();
我的AIPath包含一个名为waypoint的vector2列表。
我想知道的是我做错了什么。我想在每次更改它正在查看的路径时创建一个新路径,看起来很好。我感到困惑的是,接下来要做什么。在waypoints =(来自path.Descendants(“pathPoints”)中的i之后,我期待我必须做点什么,但我对于什么一无所知。
非常感谢任何帮助。
修改
我忘记添加一两个细节。
public class AIPath
{
//public Vector2
public List<Vector2> waypoints { get; set; }
public int linkNumber { get; set; }
public int[] potentialLinks { get; set; }
}
答案 0 :(得分:1)
目前,您的XML输出相对难以解析。我会像这样重写你的代码:
public sealed class AIPath
{
// TODO: Consider trying to make this immutable, or
// at least not exposing the collections so widely. Exposing an array
// property is almost always a bad idea.
public List<Vector2> Waypoints { get; set; }
public int LinkNumber { get; set; }
public int[] PotentialLinks { get; set; }
public XElement ToElement()
{
return new XElement("path",
WayPoints.Select(v2 => new XElement("point",
new XAttribute("X", (int) v2.X),
new XAttribute("Y", (int) v2.Y))));
}
public static AIPath FromXElement(XElement path)
{
return new AIPath
{
WayPoints = path.Elements("point")
.Select(p => new Vector2((int) p.Attribute("X"),
(int) p.Attribute("Y")))
.ToList();
};
}
}
然后:
paths = doc.Descendants("path")
.Select(x => AIPath.FromXElement(x))
.ToList();
答案 1 :(得分:1)
Jon Skeet的答案可能会有效,但XNA框架提供了一种通过内容管道将XML读入对象的更简单方法。
示例XML:
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="MyDataTypes.CatData[]">
<Item>
<Name>Rhys</Name>
<Weight>17</Weight>
<Lives>9</Lives>
</Item>
<Item>
<Name>Boo</Name>
<Weight>11</Weight>
<Lives>5</Lives>
</Item>
</Asset>
</XnaContent>
示例类:
namespace MyDataTypes
{
public class CatData
{
public string Name;
public float Weight;
public int Lives;
}
}
内置管道的内置XML导入器和处理器将在构建.xnb文件时将XML元素与正确命名的类成员相关联,假设您已正确标记了Asset Type元素。