c#中的XML元素更改值

本文关键字:元素 中的 XML | 更新日期: 2023-09-27 17:49:35

c#代码如下:

using (XmlReader Reader = XmlReader.Create(DocumentPath, XmlSettings))
{
    while (Reader.Read())
    {
        switch (Reader.NodeType)
        {
            case XmlNodeType.Element:
                //doing function
                break;
            case XmlNodeType.Text:
                if(Reader.Value.StartsWith("_"))
                {
                     // I want to replace the Reader.Value to new string
                }
                break;
            case XmlNodeType.EndElement:
                //doing function
                break;
            default:
                //doing function
                break;
        }
    }
}

我想在XmlNodeType = text时设置新值。

c#中的XML元素更改值

这个操作有3个步骤:

  1. 将文档加载为对象模型(XML是一个层次结构,如果这样更容易)
  2. 修改对象模型中的值
  3. 将模型保存为文件

加载方法取决于您,但我建议使用XDocument和相关的Linq-to-XML类来完成这样的小型任务。就像这个堆栈所展示的那样,它非常简单。

Edit -对您的场景有用的引用

XML元素可以包含文本内容。有时内容很简单(元素只包含文本内容),有时内容是混合(元素的内容同时包含文本和其他元素)元素)。在这两种情况下,每个文本块都表示为XText节点。

From MSDN - XText类

下面是一个控制台应用程序的示例代码,使用注释中的xml:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace TextNodeChange
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = @"<Info><title>a</title><content>texttexttexttexttext<tag>TAGNAME</tag>texttexttex‌​ttexttext</content>texttexttexttexttext</Info>";
            XDocument doc = XDocument.Parse(input);
            Console.WriteLine("Input document");
            Console.WriteLine(doc);
            //get the all of the text nodes in the content element
            var textNodes = doc.Element("Info").Element("content").Nodes().OfType<XText>().ToList();
            //update the second text node
            textNodes[1].Value = "THIS IS AN ALTERED VALUE!!!!";
            Console.WriteLine();
            Console.WriteLine("Output document");
            Console.WriteLine(doc);
            Console.ReadLine();
        }
    }
}

为什么需要3个步骤?

xml的元素在文件中是可变长度的。修改一个值可能会改变文件中该部分的长度,并覆盖其他部分。因此,您必须反序列化整个文档,进行更改并再次保存。

你无法取代阅读器。Value只读属性。您需要使用XmlWriter创建您自己的xml并替换您想要的任何值。