在 C# 中正确分析 XML 文件
本文关键字:XML 文件 | 更新日期: 2023-09-27 18:36:16
>我正在尝试读取保存在 xml 中的给定文件,但收到错误"对象引用未设置为对象的实例"。
编辑:我不能为此使用任何类型的序列化。
在这种情况下,
最简单的方法是使用 XmlSerializer。这不是你可以用.net做的唯一方法,因为有XmlReader,XmlTextReader和XDocument来帮助你,但XmlSerializer允许你轻松地将数据结构转换为xml并返回。下面是一个示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace TestXmlSerializer
{
class Program
{
static void Main(string[] args)
{
var g = new Group
{
Name="g2",
Keys = new[] {
new Key { Username="a" },
new Key { Password="b" }
}
};
Group g2;
var xs = new XmlSerializer(typeof(Group));
var s = string.Empty;
using (var tw = new StringWriter()) {
using (var xw = XmlWriter.Create(tw))
xs.Serialize(xw, g);
s = tw.ToString();
}
Console.WriteLine(s);
using (var ms = new StringReader(s))
{
using (var xw = XmlReader.Create(ms))
g2 = xs.Deserialize(xw) as Group;
}
Console.WriteLine(g2.Name);
}
}
[Serializable]
public class Key
{
[XmlAttribute]
public string Title;
[XmlAttribute]
public string Username;
[XmlAttribute]
public string Password;
[XmlAttribute]
public string Url;
[XmlAttribute]
public string Notes;
}
[Serializable]
public class Group
{
[XmlAttribute]
public string Name;
[XmlElement]
public Key[] Keys;
}
}