如何在 C# 中构建 XML? [英] How can I build XML in C#?

查看:19
本文介绍了如何在 C# 中构建 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中生成有效的 XML?

How can I generate valid XML in C#?

推荐答案

这取决于场景.XmlSerializer 当然是一种方式,并且具有直接映射到对象模型的优势.在.NET 3.5中,XDocument等也很友好.如果大小非常大,那么 XmlWriter 就是你的朋友.

It depends on the scenario. XmlSerializer is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, XDocument, etc. are also very friendly. If the size is very large, then XmlWriter is your friend.

对于 XDocument 示例:

Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));

或同XmlDocument:

XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);

如果您正在编写数据流,那么任何 DOM 方法(例如 XmlDocument/XDocument 等)会很快占用大量内存.因此,如果您正在从 CSV 编写一个 100MB 的 XML 文件,您可能会考虑 XmlWriter;这是更原始的(一次写入的消防水管),但非常有效(想象一下这里有一个大循环):

If you are writing a large stream of data, then any of the DOM approaches (such as XmlDocument/XDocument, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from CSV, you might consider XmlWriter; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):

XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();

最后,通过XmlSerializer:

[Serializable]
public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
    public string Nested { get; set; }
}
...
Foo foo = new Foo
{
    Bar = "some & value",
    Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);

这是一个很好的映射到类等的模型;但是,如果您正在做一些简单的事情(或者如果所需的 XML 与对象模型没有真正的直接关联),这可能是过度的.XmlSerializer 的另一个问题是它不喜欢序列化不可变类型:一切都必须有一个公共的 getter setter(除非你自己通过实现 IXmlSerializable,在这种情况下,使用 XmlSerializer 并没有获得太多好处.

This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with XmlSerializer is that it doesn't like to serialize immutable types : everything must have a public getter and setter (unless you do it all yourself by implementing IXmlSerializable, in which case you haven't gained much by using XmlSerializer).

这篇关于如何在 C# 中构建 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆