0

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.

Community
  • 1
  • 1
  • 3
    "But couldn't get it to work" doesn't explain what happens vs what you want to happen. You should also provide a short but *complete* example of your XML. Personally, I'd use LINQ to XML rather than XmlDocument, too... – Jon Skeet Mar 26 '15 at 19:52
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Mar 27 '15 at 01:14
  • I bet your XML doesn't really start with `` – John Saunders Mar 27 '15 at 01:15

3 Answers3

1

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");
Praveen Paulose
  • 5,741
  • 1
  • 15
  • 19
0

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";
EZI
  • 15,209
  • 2
  • 27
  • 33
0

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");
har07
  • 88,338
  • 12
  • 84
  • 137