我正在尝试创建一个非常简单的XML文件的快速程序.我想创建一个XML文件,该文件使用'for循环'多次创建XML的一部分.当我构建时,我得到一个错误,说"无效的表达式术语"为'.我检查我的括号平衡,它似乎确实检查出来.
有谁知道这个错误意味着什么?
static void Main(string[] args)
{
XDocument myDoc = new XDocument(
new XDeclaration("1.0" ,"utf-8","yes"),
new XElement("Start"),
for(int i = 0; i <= 5; i++)
{
new XElement("Entry",
new XAttribute("Address", "0123"),
new XAttribute("default", "0"),
new XElement("Descripion", "here is the description"),
new XElement("Data", "Data goes here ")
);
}
);
}
Run Code Online (Sandbox Code Playgroud)
您目前正在尝试for在语句中使用循环.那不行.
选项:
使用Enumerable.Range创建一个范围值,然后变换使用Select:
XDocument myDoc = new XDocument(
new XDeclaration("1.0" ,"utf-8","yes"),
// Note that the extra elements are *within* the Start element
new XElement("Start",
Enumerable.Range(0, 6)
.Select(i =>
new XElement("Entry",
new XAttribute("Address", "0123"),
new XAttribute("default", "0"),
new XElement("Descripion", "here is the description"),
new XElement("Data", "Data goes here ")))
);
Run Code Online (Sandbox Code Playgroud)首先创建文档,然后在循环中添加元素
XDocument myDoc = new XDocument(
new XDeclaration("1.0" ,"utf-8","yes"),
new XElement("Start"));
for (int i = 0; i <= 5; i++)
{
myDoc.Root.Add(new XElement("Entry",
new XAttribute("Address", "0123"),
new XAttribute("default", "0"),
new XElement("Descripion", "here is the description"),
new XElement("Data", "Data goes here "));
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |