我正在尝试编写一个C#程序,只需很少的编程经验即可获取csv文件并输出XML文件。这是有效的,但我现在尝试将程序修改为将为CSV的每一行输出XML文件的位置,并将XML文件命名为字段[0]“name”值。我不确定我做错了什么,编译器说当前上下文中不存在名称“fields”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
namespace CSVtoXML
{
class Program
{
static void Main(string[] args)
{
// Read into an array of strings.
string[] source = File.ReadAllLines("import.csv");
foreach (string line in source)
{
XElement cust = new XElement("Root",
from str in source
let fields = str.Split(',')
select new XElement("other_asset",
new XElement("name", fields[0]),
new XElement("status", new XElement("name", fields[1])),
new XElement("asset_type", new XElement("name", fields[2])),
new XElement("ip", fields[3]),
new XElement("manufacturer", fields[4]),
new XElement("model", fields[5]),
new XElement("serial_number", fields[6]),
new XElement("site", new XElement("name", fields[7])),
new XElement("department", new XElement("name", fields[8])),
new XElement("custom_field",
new XElement("location", fields[9]),
new XElement("Mac_Address", fields[10]),
new XElement("End_User", fields[11]),
new XElement("Notes", fields[12])
)
)
);
cust.Save(fields[0] + ".xml");
}
}
}
}
答案 0 :(得分:1)
编译器是对的。 fields
是局部变量,仅在LINQ查询中可见。但我认为你根本不需要LINQ查询。只需将line.Split(',')
分配给局部变量,然后使用它创建XDocument
和文件名。
像
这样的东西foreach (string line in source)
{
var fields = line.Split(',');
XElement cust =
new XElement("Root",
new XElement("other_asset",
new XElement("name", fields[0]),
new XElement("status", new XElement("name", fields[1])),
new XElement("asset_type", new XElement("name", fields[2])),
new XElement("ip", fields[3]),
new XElement("manufacturer", fields[4]),
new XElement("model", fields[5]),
new XElement("serial_number", fields[6]),
new XElement("site", new XElement("name", fields[7])),
new XElement("department", new XElement("name", fields[8])),
new XElement("custom_field",
new XElement("location", fields[9]),
new XElement("Mac_Address", fields[10]),
new XElement("End_User", fields[11]),
new XElement("Notes", fields[12])
)
)
);
cust.Save(fields[0] + ".xml");
}