我正在尝试编辑XML中的现有节点:
</floor>
<floor number="3">
<room number="301" guestname="Johan Johansen" from="14.03.2015" to="14.03.2015" />
<room number="302" guestname="Rom uten gjest" from="14.03.2015" to="14.03.2015" />
</floor>
我的代码:
XmlDocument doc = new XmlDocument();
doc.Load("Hotell.xml");
XmlNode hotel = doc.DocumentElement;
XmlNode guestname = hotel.SelectSingleNode("descendant::guestname");
guestname.Value = tb_Name.Text;
doc.Save("Hotell.xml");
我尝试了here中的代码,但我无法让它工作。
答案 0 :(得分:1)
由于声明
,这不起作用hotel.SelectSingleNode("descendant::guestname")
guestname不是节点,它是一个属性。如果您需要更改属性,则代码应为
doc.Load("Hotell.xml");
XmlNode hotel = doc.DocumentElement;
XmlNode room = hotel.SelectSingleNode("descendant::room");
room.Attributes["guestname"].Value = tb_Name.Text;
doc.Save("Hotell.xml");
答案 1 :(得分:0)
如果您想使用Linq2Xml,您的代码可以(在您的问题中修复xml之后 - 请参阅floor
标记)
string floorNum = "3";
string roomNum = "302";
var xDoc = XDocument.Load(filename);
var room = xDoc.XPathSelectElement(
String.Format("//floor[@number='{0}']/room[@number='{1}']", floorNum,roomNum));
room.Attribute("guestname").Value = "XXXXX";
答案 2 :(得分:0)
您可以通过更改参数来使SelectSingleNode()
直接返回XML属性:
XmlNode guestname = hotel.SelectSingleNode("descendant::room/attribute::guestname");
或使用相应的XPath快捷方式:
XmlNode guestname = hotel.SelectSingleNode(".//room/@guestname");