编写xml并读回c#

时间:2023-03-25
本文介绍了编写xml并读回c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

好的,我现在使用文档方法而不是 XmlWriter 来编写我的 XML.我已经编写了我的 XML 文件.

ok, I am now using the document method for writing my XML instead of the XmlWriter. I have written my XML file with.

userNode = xmlDoc.CreateElement("user");
attribute = xmlDoc.CreateAttribute("age");
attribute.Value = "39";
userNode.Attributes.Append(attribute);
userNode.InnerText = "Jane Doe";
rootNode.AppendChild(userNode);

但问题又是如何读取这些设置.

But the question is again how to read these settings back.

<users>
  <user name="John Doe" age="42" />
  <user name="Jane Doe" age="39" />
</users>

文件的格式我可以弄清楚如何读取 age 变量,但无法掌握 name 属性.我的 XML 文件与上面略有不同,但差别不大

The format of the file I can figure out how to read the age variable but can't get my hands on the name property. my XML file is slightly different to above but not by much

推荐答案

逐个元素地编写 XML 文件可能非常耗时 - 并且容易出错.

Writing XML files element by element can be quite time consuming - and susceptible to errors.

我建议对这类工作使用 XML 序列化器.

I would suggest using an XML Serializer for this type of job.

如果您不关心格式 - 并且要求只是能够序列化为 XML 并在以后反序列化,则代码可以简单如下:

If you are not concerned with the format - and the requirement is just to be able to serialize to XML and deserialize at a later time the code can be as simple as follows:

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

string filepath = @"c:	empusers.xml";

var usersToStore = new List<User>
{
     new User { Name = "John Doe", Age = 42 },
     new User { Name = "Jane Doe", Age = 29 }
};

using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
{
    XmlSerializer serializer = new XmlSerializer(usersToStore.GetType());
    serializer.Serialize(fs, usersToStore);
}

 var retrievedUsers = new List<User>();
 using (FileStream fs2 = new FileStream(filepath, FileMode.Open))
 {
     XmlSerializer serializer = new XmlSerializer(usersToStore.GetType());
     retrievedUsers = serializer.Deserialize(fs2) as List<User>;
 }

Microsoft 在 .Net 文档中提供了一些很好的示例- 介绍 XML 序列化

Microsoft provides some good examples in the .Net documentation - Introducing XML Serialization

这篇关于编写xml并读回c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用 C#、LINQ 从 xml 字符串中读取子节点 下一篇:C# 将根添加到 XDocument

相关文章