简体   繁体   English

如何使用C#读取和编辑XML文件?

[英]How can I read and edit an XML file using C#?

How can I open and edit an existing XML file? 如何打开和编辑现有XML文件? I would like to modify some values like: 我想修改一些值,如:

<address>myaddr</address>

For example, I would like to put loreal instead if myaddr. 例如,如果myaddr,我想把loreal。 I am working in C#. 我在C#工作。 I would appreciate if you can show me some code. 如果你能告诉我一些代码,我将不胜感激。

You could use the XDocument class: 您可以使用XDocument类:

var doc = XDocument.Load("test.xml");
var address = doc.Root.Element("address");
if (address != null)
{
    address.Value = "new value";
}
doc.Save("test.xml");

Let's say you have the following XML file: 假设您有以下XML文件:

<root>
    <address>myaddr</address>
</root>

And you want to do the replacement. 你想要做替换。 There are many options. 有很多选择。 Some are explicitly modifying XML, others are translating your XML to classes, modifying and translating back to XML (serialization). 有些是显式修改XML,有些是将XML转换为类,修改和转换回XML(序列化)。 Here is one of the ways do do it: 以下是其中一种方法:

XDocument doc = XDocument.Load("myfile.xml");
doc.Root.Element("address").Value = "new address"
doc.Save("myfile.xml")

For more information read the following: 有关更多信息,请阅读以下内容

  1. LINQ to XML is the technique I used here - http://msdn.microsoft.com/en-us/library/bb387098.aspx LINQ to XML是我在这里使用的技术 - http://msdn.microsoft.com/en-us/library/bb387098.aspx

  2. XML serialization is another technique - http://msdn.microsoft.com/en-us/library/182eeyhh.aspx XML序列化是另一种技术 - http://msdn.microsoft.com/en-us/library/182eeyhh.aspx

Yes, that's totally possible - and quite easily, too. 是的,这完全有可能 - 而且很容易。

Read those resources: 阅读这些资源:

and a great many more - just search for "Intro Linq-to-XML" or "Intro XMLDocument" - you'll get plenty of links to good articles and blog posts. 还有更多 - 只需搜索“Intro Linq-to-XML”或“Intro XMLDocument” - 您将获得大量有关优秀文章和博客文章的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM