我正在创建一个XDocument的小问题。我试图在文档创建中使用foreach循环,但我不知道如何将它拉下来。 代码:
部分代码:
XDocument doc = null;
doc = new XDocument(
new XDeclaration("1.0", "ISO-8859-1", "no"),
new XElement("data",
new XElement("meta",
new XElement("val",
new XAttribute("n", "printer"), DropDownPrinters.SelectedItem.Text),
new XElement("val",
new XAttribute("n", "autoprint"), "YES"),
new XElement("val",
new XAttribute("n", "test"), 0)
), //after this I need to loop through datarows, something like this
foreach (DataTable dt in ds3.Tables)
{
foreach (DataRow dr in dt.Rows)
{
new XElement("something",
new XAttribute("something", dr.Field<string>("3")),
new XElement("val",
new XAttribute("n", "something"), dr.Field<string>("0") + " " + dr.Field<string>(4) + " " + dr.Field<string>(5)),
new XElement("val",
new XAttribute("n", "something"), dr.Field<string>("0")),
new XElement("val",
new XAttribute("n", "something"), dr.Field<string>("0")),
new XElement("val",
new XAttribute("n", "something"), dr.Field<string>("0")),
new XElement("val",
new XAttribute("n", "something"), "SE"),
new XElement("val",
new XAttribute("n", "something"), dr.Field<string>("0")),
new XElement("val",
new XAttribute("n", "something"))
);
}}
答案 0 :(得分:0)
使用LINQ而不是foreach
,如下所示:
var something = from dt in ds.Tables.OfType<DataTable>()
from dr in t.AsEnumerable()
select
new XElement("something",
new XAttribute("something", dr.Field<string>("3")),
......
......
);
然后,您可以将变量something
放在foreach
所在的位置。