Using c# variable in XPath to change the value

637 Views Asked by At

I need to change /price in the XML document using C#, but I can't figure out how to select the node to change it's value.

        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Users\Wurf\Desktop\c#\books.xml");
            Console.WriteLine("Podaj ID książki której cenę chcesz zmienić.");
            string idKsiazki = "bk" + Console.ReadLine();
            XmlNode wezel = doc.SelectSingleNode("//book[@id=" + idKsiazki + "]/price");
            Console.WriteLine("Podaj nową cenę książki.");
            wezel.Value = Console.ReadLine();
            doc.Save(@"C:\Users\Wurf\Desktop\c#\books.xml");

Here's a part of the XML Document

<catalog>
  <book id="bk101" genre="Computer">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
1

There are 1 best solutions below

0
Innat3 On

Here's a way to do it following your sample code

var doc = XDocument.Load(xmlFilePath); 
var books = doc.Descendants().Where(x => x.Name == "book");

string requestedBookId = Console.ReadLine();
var requestedBook = books.FirstOrDefault(x => x.Attribute("id").Value == requestedBookId);

if (requestedBook == null)
{
    Console.WriteLine($"book with id '{requestedBookId}' not found");
}
else
{
    var price = requestedBook.Descendants().First(x => x.Name == "price");
    price.Value = Console.ReadLine();
    doc.Save(xmlFilePath);
    Console.WriteLine("price updated!");
}