我正在尝试将我的战舰游戏保存到XML,到目前为止它已经相当不错了。我在XML文件中保存的是玩家名称,船只和未命中的坐标。
船舶的ID属性是知道哪个船舶坐标构成一艘船。接下来是通过向正确的元素添加属性来标记每艘船已被击中,并且我知道通过它的值得到什么元素。
但我不知道如何得到它。我找到的只是XElement
name
以及具有该名称的所有元素。
<?xml version="1.0" encoding="UTF-8" ?>
<Players>
<Playerboard>
<Name>Player</Name>
<Ships>
<ship id="1213">12_13</ship>
<ship id="1213">12_14</ship>
<ship id="1211">12_11</ship>
<ship id="1211">12_12</ship>
</Ships>
<Misses>
<Miss>3_9</Miss>
<Miss>9_12</Miss>
<Miss>10_12</Miss>
</Misses>
</Playerboard>
<Computerboard>
<Name>AI</Name>
<Ships>
<ship id="1010">10_10</ship>
<ship id="1010">10_11</ship>
<ship id="1010">10_12</ship>
<ship id="1010">10_13</ship>
<ship id="11">1_1</ship>
<ship id="11">2_1</ship>
</Ships>
<Misses>
<Miss>0_2</Miss>
<Miss>0_3</Miss>
<Miss>1_3</Miss>
</Misses>
</Computerboard>
</Players>
这是因为我试图获得正确的元素,这不起作用。 &#34; K&#34;在我下面的例子中一直是空的。
XElement e = xelement.Element("Playerboard");
var ships = from s in e.Elements("Ships")
where (string)s.Element("ship") == x + "_" +y
select s;
foreach (XElement k in ships)
{
Console.WriteLine(k);
}
例如,我想为船舶添加一个值为12_12的属性,我该怎么做?
答案 0 :(得分:2)
这对我来说很好用:
var doc = XDocument.Parse(xml);
var elements =
doc
.Root //Ignore the root
.Element("Playerboard") //The Playerboard element.
.Element("Ships") //There's only one Ships element.
.Elements("ship") //Get all the ship elements from Ships.
.Where(ship => ship.Value == "12_12"); //.Value is a little more explicit but you
//want strings anyway.
foreach (var element in elements)
{
Console.WriteLine(element);
element.Add(new XAttribute("Name", "Value")); //Adding your new attribute.
Console.WriteLine(element);
}
我使用lambda语法因为我更喜欢它(对不起,它只是让我更清楚我正在做的事情。)
如果您只希望一个ship
元素与给定值匹配,那么您最后可以使用.Single()
来避免收集。
答案 1 :(得分:0)
你也可以这样做:
int x = 12, y = 12;
var doc = XDocument.Load("[path of your xml]");
//Finding the playerboard, by your structure I suppose you have one
var playerBoard= doc.Descendants("Playerboard").FirstOrDefault();
var ship = playerBoard.Element("Ships").Elements("ship").FirstOrDefault(e => e.Value == x + "_" + y);
//Adding an attribute to the ship
ship.Add(new XAttribute("Foo", "Boo"));