【问题标题】:Update multiple XML nodes that match an Xpath query C#更新与 Xpath 查询匹配的多个 XML 节点 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? 

    }

【问题讨论】:

    标签: c# xml xpath


    【解决方案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 ;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多