编写xml并读回c#

Writing xml and reading it back c#(编写xml并读回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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)