简体   繁体   English

使用 XPath 中的 c# 变量更改值

[英]Using c# variable in XPath to change the value

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.我需要使用 C# 更改 XML 文档中的 /price,但我不知道如何通过 select 节点更改其值。

        {
            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这是 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>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM