更新与 Xpath 查询匹配的多个 XML 节点 C#
Posted
技术标签:
【中文标题】更新与 Xpath 查询匹配的多个 XML 节点 C#【英文标题】:Update multiple XML nodes that match an Xpath query C# 【发布时间】:2020-09-24 20:40:43 【问题描述】:我正在尝试更新与特定 xpath 匹配的多个节点的内容。例如,在下面的示例中,我想用“Hello”更新当前为“2”的任何 attribute1 节点。最好的方法是什么?
(DotNetFiddle Here)
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
public static void Main()
XmlDocument job = new XmlDocument();
job.LoadXml(@"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
【问题讨论】:
【参考方案1】:这可能会对您有所帮助:
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
public static void Main()
XmlDocument job = new XmlDocument();
job.LoadXml(@"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
// getting the list of nodes with XPath query :
XmlNodeList nodes = job.SelectNodes("//attribute1[text()=2]");
foreach (XmlNode child in nodes)
// replacing the old value with the new value
child.InnerText = newAttribute1Value ;
【讨论】:
以上是关于更新与 Xpath 查询匹配的多个 XML 节点 C#的主要内容,如果未能解决你的问题,请参考以下文章
使用 XSLT 基于 ID 从多个 xPath 中选择 XML 节点
XML 使用 Xpath 来多节点属性匹配查询 具体如下: XML文档 <?xml version="1.0" encoding="utf-8"?>