首页 > 解决方案 > 在 XPath 中使用 c# 变量来更改值

问题描述

我需要使用 C# 更改 XML 文档中的 /price,但我不知道如何选择节点来更改它的值。

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

这是 XML 文档的一部分

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

标签: c#xpathselectnodes

解决方案


这是按照您的示例代码执行此操作的方法

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

推荐阅读