C# 将对象集合导出到 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/570288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:39:26  来源:igfitidea点击:

Export object collection to XML file

c#xmlcollectionsexport

提问by MattSlay

Using C#...I have a small app that creates objects from a class, and adds them to an object collection and it does some UI stuff along the way to display certain values from the currently selected object in the collection (Using WPF UI). So I want to add the ability to let the user save his object collection to a file, so they can load it back the next time they run the app.

使用 C#...我有一个小应用程序,它从一个类中创建对象,并将它们添加到一个对象集合中,它会在显示集合中当前选定对象的某些值的过程中执行一些 UI 操作(使用 WPF UI) . 所以我想添加一个功能,让用户将他的对象集合保存到一个文件中,这样他们就可以在下次运行应用程序时重新加载它。

I'm guessing XML is an obvious way to go, but I know nothing about how to do it. So, how do you export or dump a collection of objects to an xml file, and then, perhaps more importantly, how would I then read that XML file back into my app to re-create the collection?

我猜 XML 是一种显而易见的方法,但我对如何去做一无所知。那么,您如何将对象集合导出或转储到 xml 文件,然后,也许更重要的是,我将如何将该 XML 文件读回我的应用程序以重新创建该集合?

Here is a screenshot of the app

这是应用程序的屏幕截图

回答by ZombieSheep

System.Runtime.Serializationis your friend here, if you decide to go for XML.

如果您决定使用 XML,System.Runtime.Serialization是您的朋友。

In one of my test apps, I sometimes need to be able to serialise an object as XML so I can look at it all offline. Here's the snippet I use (not optimised in any way, just quickly knocked together one day, and it has worked as I needed it).

在我的一个测试应用程序中,我有时需要能够将对象序列化为 XML,以便我可以离线查看它。这是我使用的代码片段(没有以任何方式进行优化,只是有一天快速组合在一起,它已经按照我的需要工作了)。

public static string ObjectToXml<T>(T objectToSerialise)
{
    StringWriter Output = new StringWriter(new StringBuilder());
    XmlSerializer xs = new XmlSerializer(objectToSerialise.GetType());
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("MyNs", "http://www.someXmlNamespace/namespace1"); // add as many or few as you need
    xs.Serialize(Output, objectToSerialise, ns);
    return Output.ToString();
}

After that, it's trivial to squirt the data out to a file.

之后,将数据喷出到文件中就很简单了。

Notes:
I needed to be able to get the XML content as a string so I could persist it one of several ways. Building a method to go direct to disk would be easy too, if that's what you need.
Although this works for me, you may need to tweak to meet your own needs.

注意
我需要能够将 XML 内容作为字符串获取,以便我可以通过多种方式之一将其持久化。如果您需要,构建直接访问磁盘的方法也很容易。
虽然这对我有用,但您可能需要进行调整以满足您自己的需求。

回答by Matt Jordan

There are a ton of topics on StackOverflow about XML Serialization, including a few excellent posts regarding some hidden gotchyas:

StackOverflow 上有很多关于 XML 序列化的主题,包括一些关于一些隐藏问题的优秀帖子:

Saving Data Structures using Serialization

使用序列化保存数据结构

Serialization Gotchyas

序列化问题

回答by DMCS

XML Serialization is OK and good for many situations, but the output will be a little bulky due to XML inherent overhead. In this situation where the file's contents don't need to be human readable, so this opens up other options.

XML 序列化在很多情况下都很好,但由于 XML 固有的开销,输出会有点庞大。在这种情况下,文件的内容不需要是人类可读的,因此这会打开其他选项。

JSON serialization will help keep the file size down. JavaScriptSerializer can be found in System.Web.Script.Serialization (System.Web.Extensions.dll).

JSON 序列化将有助于减小文件大小。JavaScriptSerializer 可以在 System.Web.Script.Serialization (System.Web.Extensions.dll) 中找到。

In the example below I have a Typed generic list of ConfigurationItem. Configuration item is like any other class but the properties should be public for them to be serialized.

在下面的示例中,我有一个类型化的 ConfigurationItem 通用列表。配置项就像任何其他类,但属性应该是公开的,以便它们被序列化。

var strFileData = System.IO.File.ReadAllText("FileName.data");
var jss = new JavaScriptSerializer();
var objItemsList = jss.Deserialize<List<ConfigurationItem>>(strFileData);
// {insert code here tomanipulate object "objItemsList"}
var strNewData = jss.Serialize(objItemsList);
System.IO.File.WriteAllText("FileName.data", strNewData);

回答by benPearce

The problem with Serialisation to XML is that if your class being serialised changes (new property), then the xml cannot be used to recreate the instance of that class.

序列化到 XML 的问题在于,如果正在序列化的类发生更改(新属性),则 xml 不能用于重新创建该类的实例。

If the class is fairly simple (or even if it is not) you could do it manually:

如果课程相当简单(或者即使不是),您可以手动完成:

XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateNode(XmlNodeType.Element,"root")
doc.AppendChild(root)
XmlNode newPage = doc.CreateNode(XmlNodeType.Element,"pattern")
root.AppendChild(newPage)
newPage.Attributes.Append(doc.CreateAttribute("Name",pattern.Name)
foreach (Hole h in pattern.Holes)
{
  XmlNode hole = doc.CreateNode(XmlNodeType.Element,"hole")
  hole.Attributes.Append(doc.CreateAttribute("XCoord",h.Xcoord)
  hole.Attributes.Append(doc.CreateAttribute("YCoord",h.Ycoord)
  newPage.AppendChild(hole)
}
// etc
doc.Save("output.xml")

This code is rough, but it would generate something like:

这段代码很粗糙,但它会生成如下内容:

<root>
  <pattern name="Pattern1">
    <hole XCoord="100" YCoord="50" />
  </pattern>
</root>