【问题标题】:How can i make a xml file from a multidimentional array in C#?如何从 C# 中的多维数组创建 xml 文件?
【发布时间】:2013-11-07 23:36:40
【问题描述】:

我根据存储在我的多维数组中的数据制作一个 xml 文件作为报告,就像这样:

string[,] twoDimentionArray = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} }; 

如何在 C# 中从这个数组创建一个 xml 文件?

谢谢。

【问题讨论】:

  • 你希望你的 XML 看起来像什么?

标签: c# xml arrays serialization


【解决方案1】:

使用XmlSerializer Class

在 XML 文档中序列化和反序列化对象。这 XmlSerializer 使您能够控制如何将对象编码为 XML。

【讨论】:

    【解决方案2】:

    如果您不想创建一个类来表示数据以使用序列化器,您也可以使用XDocument(尽管我个人建议您这样做,因为任何数据结构都比您拥有的更复杂您的样品将很快成为维护问题!)

    请注意,为了清楚起见,这段代码是故意“长手”的,您可能可以在单个嵌套语句中完成。

    string[,] twoDimentionArray = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} }; 
    var doc = new XDocument();
    var Couples = new XElement("Couples");
    doc.Add(Couples);
    for(int x=0;x<2;x++)
    {
        var couple= new XElement("Couple");
        couple.Add(new XElement("Person1",twoDimentionArray[x,0]));
        couple.Add(new XElement("Person2",twoDimentionArray[x,1]));
        Couples.Add(couple);
    }
    Console.WriteLine(doc.ToString());
    

    会产生

    <Couples>
      <Couple>
        <Person1>Mike</Person1>
        <Person2>Amy</Person2>
      </Couple>
      <Couple>
        <Person1>Mary</Person1>
        <Person2>Albert</Person2>
      </Couple>
    </Couples>
    

    【讨论】:

    • 谢谢!它将在其他示例中帮助我,非常感谢。
    • 没问题,但请检查 m。从长远来看,埃德蒙森作为XmlSerializer 的回答将证明对您更有帮助!
    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2012-11-07
    相关资源
    最近更新 更多