c# - 在 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>
解决方案
这是按照您的示例代码执行此操作的方法
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!");
}
推荐阅读
- javascript - 如何使用纯 JavaScript 处理某些元素中的元素?
- c# - Word,如何在单元格末尾粘贴字母或符号?
- sql - 获取分层表中子列表的根元素
- winapi - 光盘的递归路径:Time to long C++
- mysql - SequelizeEagerLoadingError:产品未与集合关联
- python - VScode 声称安装了 Python,但我已经安装了 python 3.8 和 anaconda3
- macos - 为 GitHub Actions macOS 自托管运行器提供密码
- android - Android 从播放器录制相机和音乐
- gpu - 带有 Vulkan 的外部 GPU
- type-conversion - 将无符号整数与有符号类型进行比较