如何在 C# 中构建 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/284324/
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-03 21:36:57  来源:igfitidea点击:

How can I build XML in C#?

c#xml

提问by Dan Esparza

How can I generate valid XML in C#?

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

采纳答案by Marc Gravell

It depends on the scenario. XmlSerializeris 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 XmlWriteris your friend.

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

For an XDocumentexample:

对于一个XDocument例子:

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

Or the same with XmlDocument:

或与以下相同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);

If you are writing a largestream 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):

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

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

Finally, via XmlSerializer:

最后,通过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);

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 XmlSerializeris that it doesn't like to serialize immutable types : everything must have a public getter andsetter (unless you do it all yourself by implementing IXmlSerializable, in which case you haven't gained much by using XmlSerializer).

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

回答by Mikael S?derstr?m

XmlWriter is the fastest way to write good XML. XDocument, XMLDocument and some others works good aswell, but are not optimized for writing XML. If you want to write the XML as fast as possible, you should definitely use XmlWriter.

XmlWriter 是编写好的 XML 的最快方法。XDocument、XMLDocument 和其他一些也可以很好地工作,但没有针对编写 XML 进行优化。如果您想尽可能快地编写 XML,则绝对应该使用 XmlWriter。

回答by FlySwat

For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.

对于简单的事情,我只使用 System.XML 中的 XmlDocument/XmlNode/XmlAttribute 类和 XmlDocument DOM。

It generates the XML for me, I just need to link a few items together.

它为我生成 XML,我只需要将几个项目链接在一起。

However, on larger things, I use XML serialization.

但是,在更大的事情上,我使用 XML 序列化。

回答by Todd

For simple cases, I would also suggest looking at XmlOutputa fluent interface for building Xml.

对于简单的情况,我还建议查看XmlOutput一个用于构建 Xml 的流畅接口。

XmlOutput is great for simple Xml creation with readable and maintainable code, while generating valid Xml. The orginal posthas some great examples.

XmlOutput 非常适合使用可读和可维护的代码创建简单的 Xml,同时生成有效的 Xml。该原单后有一些很好的例子。

回答by Bob

In the past I have created my XML Schema, then used a tool to generate C# classes which will serialize to that schema. The XML Schema Definition Tool is one example

过去我创建了我的 XML 架构,然后使用一个工具来生成将序列化为该架构的 C# 类。XML Schema Definition Tool 就是一个例子

http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

回答by GurdeepS

As above.

如上。

I use stringbuilder.append().

我使用 stringbuilder.append()。

Very straightforward, and you can then do xmldocument.load(strinbuilder object as parameter).

非常简单,然后您可以执行 xmldocument.load(strinbuilder object as parameter)。

You will probably find yourself using string.concat within the append parameter, but this is a very straightforward approach.

您可能会发现自己在 append 参数中使用了 string.concat,但这是一种非常简单的方法。

回答by GurdeepS

The best thing hands down that I have tried is LINQ to XSD(which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still "Preview", I have not encountered any bugs with it.

我尝试过的最好的事情是LINQ to XSD(大多数开发人员都不知道)。你给它一个 XSD 模式,它在后台为你生成一个完美映射的完整强类型对象模型(基于 LINQ to XML),这真的很容易使用 - 它更新和验证你的对象模型和 XML即时的。虽然它仍然是“预览版”,但我没有遇到任何错误。

If you have an XSD Schema that looks like this:

如果您有一个如下所示的 XSD 架构:

  <xs:element name="RootElement">
     <xs:complexType>
      <xs:sequence>
        <xs:element name="Element1" type="xs:string" />
        <xs:element name="Element2" type="xs:string" />
      </xs:sequence>
       <xs:attribute name="Attribute1" type="xs:integer" use="optional" />
       <xs:attribute name="Attribute2" type="xs:boolean" use="required" />
     </xs:complexType>
  </xs:element>

Then you can simply build XML like this:

然后你可以像这样简单地构建 XML:

RootElement rootElement = new RootElement;
rootElement.Element1 = "Element1";
rootElement.Element2 = "Element2";
rootElement.Attribute1 = 5;
rootElement.Attribute2 = true;

Or simply load an XML from file like this:

或者简单地从文件中加载一个 XML,如下所示:

RootElement rootElement = RootElement.Load(filePath);

Or save it like this:

或者像这样保存:

rootElement.Save(string);
rootElement.Save(textWriter);
rootElement.Save(xmlWriter);

rootElement.Untypedalso yields the element in form of a XElement (from LINQ to XML).

rootElement.Untyped还生成 XElement 形式的元素(从 LINQ 到 XML)。

回答by Vincent

new XElement("Foo",
       from s in nameValuePairList
       select
             new XElement("Bar",
                  new XAttribute("SomeAttr", "SomeAttrValue"),
                          new XElement("Name", s.Name),
                          new XElement("Value", s.Value)
                         )
            );

回答by swdev

I think this resource should suffice for a moderate XML save/load: Read/Write XML using C#.

我认为此资源应该足以进行适度的 XML 保存/加载:使用 C# 读取/写入 XML

My task was to store musical notation. I choose XML, because I guess .NEThas matured enough to allow easy solution for the task. I was right :)

我的任务是存储乐谱。我选择 XML,因为我猜.NET已经足够成熟,可以为任务提供简单的解决方案。我是对的 :)

This is my song file prototype:

这是我的歌曲文件原型:

<music judul="Kupu-Kupu yang Lucu" pengarang="Ibu Sud" tempo="120" birama="4/4" nadadasar="1=F" biramapembilang="4" biramapenyebut="4">
    <not angka="1" oktaf="0" naikturun="" nilai="1"/>
    <not angka="2" oktaf="0" naikturun="" nilai="0.5"/>
    <not angka="5" oktaf="1" naikturun="/" nilai="0.25"/>
    <not angka="2" oktaf="0" naikturun="\" nilai="0.125"/>
    <not angka="1" oktaf="0" naikturun="" nilai="0.0625"/>
</music>

That can be solved quite easily:

这可以很容易地解决:

For Save to File:

对于保存到文件:

 private void saveToolStripMenuItem_Click(object sender, EventArgs e)
 {
     saveFileDialog1.Title = "Save Song File";
     saveFileDialog1.Filter = "Song Files|*.xsong";
     if (saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
         FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
         XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
         w.WriteStartDocument();
         w.WriteStartElement("music");
         w.WriteAttributeString("judul", Program.music.getTitle());
         w.WriteAttributeString("pengarang", Program.music.getAuthor());
         w.WriteAttributeString("tempo", Program.music.getTempo()+"");
         w.WriteAttributeString("birama", Program.music.getBirama());
         w.WriteAttributeString("nadadasar", Program.music.getNadaDasar());
         w.WriteAttributeString("biramapembilang", Program.music.getBiramaPembilang()+"");
         w.WriteAttributeString("biramapenyebut", Program.music.getBiramaPenyebut()+"");

         for (int i = 0; i < listNotasi.Count; i++)
         {
             CNot not = listNotasi[i];
             w.WriteStartElement("not");
             w.WriteAttributeString("angka", not.getNot() + "");
             w.WriteAttributeString("oktaf", not.getOktaf() + "");
             String naikturun="";
             if(not.isTurunSetengah())naikturun="\";
             else if(not.isNaikSetengah())naikturun="/";
             w.WriteAttributeString("naikturun",naikturun);
             w.WriteAttributeString("nilai", not.getNilaiNot()+"");
             w.WriteEndElement();
         }
         w.WriteEndElement();

         w.Flush();
         fs.Close();
     }

 }

For load file:

对于加载文件:

openFileDialog1.Title = "Open Song File";
openFileDialog1.Filter = "Song Files|*.xsong";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
    XmlTextReader r = new XmlTextReader(fs);

    while (r.Read())
    {
        if (r.NodeType == XmlNodeType.Element)
        {
            if (r.Name.ToLower().Equals("music"))
            {
                Program.music = new CMusic(r.GetAttribute("judul"),
                    r.GetAttribute("pengarang"),
                    r.GetAttribute("birama"),
                    Convert.ToInt32(r.GetAttribute("tempo")),
                    r.GetAttribute("nadadasar"),
                    Convert.ToInt32(r.GetAttribute("biramapembilang")),
                    Convert.ToInt32(r.GetAttribute("biramapenyebut")));
            }
            else
                if (r.Name.ToLower().Equals("not"))
                {
                    CNot not = new CNot(Convert.ToInt32(r.GetAttribute("angka")), Convert.ToInt32(r.GetAttribute("oktaf")));
                    if (r.GetAttribute("naikturun").Equals("/"))
                    {
                        not.setNaikSetengah();
                    }
                    else if (r.GetAttribute("naikturun").Equals("\"))
                    {
                        not.setTurunSetengah();
                    }
                    not.setNilaiNot(Convert.ToSingle(r.GetAttribute("nilai")));
                    listNotasi.Add(not);
                }
        }
        else
            if (r.NodeType == XmlNodeType.Text)
            {
                Console.WriteLine("\tVALUE: " + r.Value);
            }
    }
}

}
}