在运行时从DataTable向XDocument添加元素

时间:2014-05-25 05:33:36

标签: c# .net xml linq-to-xml

我试图通过在运行时从XDocument提取数据来使用DataTable生成XML。我希望以这种格式输出:

<Document>
  <Alphabets>
    <Data>
      <Capital>AAA</Capital>
      <Small>aaa</Small>
    </Data>    
  </Alphabets>
  <Language>
      <Name>English</Name>
  </Language>
  <Alphabets>
    <Data>
      <Capital>BBB</Capital>
      <Small>bbb</Small>
    </Data>
  </Alphabets>
  <Language>
      <Name>English</Name>
  </Language>
</Document>

Language元素必须在每个Alphabets元素后出现。我已经非常努力地实现了这一点,但我无法在每个Alphabets元素之后添加此Language标记。我所取得的成就是Language元素落入Alphabets元素:

<Document>
  <Alphabets>
    <Data>
      <Capital>AAA</Capital>
      <Small>aaa</Small>
    </Data>
    <Language>
      <Name>English</Name>
    </Language>
  </Alphabets>
  <Alphabets>
    <Data>
      <Capital>BBB</Capital>
      <Small>bbb</Small>
    </Data>
    <Language>
      <Name>English</Name>
    </Language>
  </Alphabets>
</Document>  

这是我的代码:

        static void Main(string[] args)
        {
            DataTable dtAlpha = new DataTable("Alphabetss");
            dtAlpha.Columns.Add("Capital", typeof(string));
            dtAlpha.Columns.Add("Small", typeof(string));

            dtAlpha.Rows.Add("AAA", "aaa");
            dtAlpha.Rows.Add("BBB", "bbb");

            XDocument doc = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),
                new XElement("Document",
                        from row in dtAlpha.AsEnumerable()
                        select new XElement("Alphabets",
                            new XElement("Data",
                                new XElement("Capital", row.Field<string>("Capital")),
                                new XElement("Small", row.Field<string>("Small"))
                                         ),
                        new XElement("Language",
                            new XElement("Name", "English")
                            )))
                            );
            Console.WriteLine(doc.ToString());
            Console.ReadKey();
        }  

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以尝试这种方式:

XDocument doc = new XDocument(
    new XDeclaration("1.0", "UTF-8", null),
    new XElement("Document")
);

foreach(var row in dtAlpha.AsEnumerable())
{
    var alphabets = new XElement("Alphabets",
                        new XElement("Data",
                            new XElement("Capital", row.Field<string>("Capital")),
                            new XElement("Small", row.Field<string>("Small"))
                        )
                    );
    var language = new XElement("Language",
                        new XElement("Name", "English")
                    );
    doc.Root.Add(alphabets);
    doc.Root.Add(language);
}