问题描述
好的,我现在使用文档方法而不是 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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)