Writing xml and reading it back c#(编写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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:编写xml并读回c#
基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
