我试图通过在运行时从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();
}
请帮我解决这个问题。
答案 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);
}