Inger Horn
Inger Horn

Reputation: 3

Edit existing node in XML doc

I'm trying to edit an existing node in my 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>

My code:

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"); 

I tried the code from here, but I couldn't get it to work.

Upvotes: 0

Views: 88

Answers (3)

har07
har07

Reputation: 89305

You can make SelectSingleNode() returns the XML attribute directly by changing the parameter like so :

XmlNode guestname = hotel.SelectSingleNode("descendant::room/attribute::guestname");

or using corresponding XPath shortcut :

XmlNode guestname = hotel.SelectSingleNode(".//room/@guestname");

Upvotes: 0

Praveen Paulose
Praveen Paulose

Reputation: 5771

This is not working because of the statement

hotel.SelectSingleNode("descendant::guestname")

guestname is not a node, it is an attribute. If you need to change the attribute your code should be

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");

Upvotes: 1

EZI
EZI

Reputation: 15364

If you want to use Linq2Xml, your code can be (after fixing the xml in your question - see the floor tags)

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";

Upvotes: 0

Related Questions