改变一个元素在C#中的价值的最佳方式元素、价值、方式

2023-09-02 10:55:52 作者:Reluctantly(勉强)

我想看看改变XML元素的价值的最佳途径。

I'm trying to look at the best way of changing the value of an element in XML.

<MyXmlType>
   <MyXmlElement>Value</MyXmlElement>
</MyXmlType>

什么是改变价值在C#中最简单的和/或最佳方式是什么?

What is the easiest and/or best way to change "Value" in C#?

我看的XMLDocument,这将导致整个XML文档加载到内存中。你能与XMLReader可以安全地做到这一点。问题是改变的价值,并发射回似乎是一个有趣的难题。

I've looked at XMLDocument and it will cause a load of the whole XML document to memory. Could you do it safely with the XMLReader. The problem is changing the value and emitting it back seems like an interesting conundrum.

干杯:D

推荐答案

您可以使用System.Xml.Linq的空间工具和最易读的code。这将加载整个文件到内存中。

You could use the System.Xml.Linq namespace stuff for the easiest to read code. This will load the full file into memory.

        XDocument xdoc = XDocument.Load("file.xml");
        var element = xdoc.Elements("MyXmlElement").Single();
        element.Value = "foo";
        xdoc.Save("file.xml");