c# - 编写 XML 文件?

标签 c# xml xml-serialization linq-to-xml

我正在尝试编写 XML 文件。

我有一个配置列表。

[Serializable]
public class Configuration
{
    public decimal X { get; set; }
    public decimal Y { get; set; }
}

这是我的属性(property)。

    [XmlArray("Configurations")]
    [XmlArrayItem("Configuration")]
    public List<Configuration> Configurations { get;set; }

调用者是:

    this.Configurations = new List<Configuration>()
    {
        new Configuration() { X = 1, Y = 10 },
        new Configuration() { X = 10, Y = 100 },
    };

    string filename = "test.xml";

    TextWriter writer = new StreamWriter(filename);
    XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>));
    serializer.Serialize(writer, this.Configurations));
    writer.Close();

输出是:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Configuration x="1" y="10" />
  <Configuration x="10" y="100" />
</ArrayOfConfiguration>

有办法可以生成这个 XML 文件吗?

<?xml version="1.0" encoding="utf-8"?> 
<Configurations>
  <Configuration X="1" Y="10" />
  <Configuration X="10" Y="100" />
</Configurations>

有没有办法以这种方式生成它们?

最佳答案

尝试使用以下属性:

[XmlArray("Configurations")]
[XmlArrayItem("Configuration")]

关于c# - 编写 XML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9336555/

相关文章:

c# - 覆盖 XmlSerialization 的类名

c# - XAML 停止列表框文本样式在散焦时更改

android - 我有一个用 XML 制作的自定义编辑文本,仅在 KITKAT 版本中它具有黑色背景

当模式来自类路径时,Java XML 验证不起作用

android - 在 Android 元素中使用 CSS

c# - 反序列化 XML 文件的最有效方法是什么

c# - 请求期间使用 WCF 的 System.OutOfMemoryException

c# - 如何获取像 ReadOnlySpan 这样的 ref 结构的 sizeof?

c# - Azure Active Directory 不会使用 ASP.NET Core 2.1 MVC 注销

java - 以 XML 格式表示带有循环、流动的电路?