我有一个文件,其中包含我用来创建XML的CSV条目。现在我用通用名称保存它,但我想要做的是使用节点的值或多个节点的组合作为xml文件的名称,因此它是唯一的。
例如,
C:\LOGGER 20150119\013521sa.au,Line01,20150119,013521,value,Yes,No,Out,7652816686,1,something,2220
我希望将文件另存为
C:/Line01_value.xml.
这可能吗?这就是我现在用来创建xml的内容:
string[] lines = File.ReadAllLines(@"C:\file.csv");
XElement xml = new XElement("root",
from str in lines
let columns = str.Split(',')
select new XElement("recording_info",
new XElement("recorded_accound_id", columns[1]),//Line01
new XElement("date_created_ts", String.Format("{0:####-##-## ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))), //date
new XElement("recorded_cid", columns[9]),//1
new XElement("recording_tag", columns[1]),//Line01
new XElement("from_caller_id", columns[10] + " <"+columns[8]+ ">")//ball memorial H
) );
xml.Save(@"C:\XMLFile.xml");<<I want to change this..
编辑:所有这一切是因为我有一个包含多个csv条目的CSV,我需要为每个条目创建一个XML并使用xml / csv中的值保存它,这样它就是唯一的
答案 0 :(得分:2)
对于文件中的每一行,使用匿名类型的新对象获取文件名和要保存的XElement(我在此处删除了&#39; root&#39;节点),然后保存文件:
string[] lines = File.ReadAllLines(@"C:\file.csv");
var xmls = (from str in lines
let columns = str.Split(',')
select new
{
XFILENAME = columns[1] + "_" + columns[4],
XELEM = new XElement("recording_info",
new XElement("recorded_accound_id", columns[1]),//Line01
new XElement("date_created_ts", String.Format("{0:####-##-## ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))), //date
new XElement("recorded_cid", columns[9]),//1
new XElement("recording_tag", columns[1]),//Line01
new XElement("from_caller_id", columns[10] + " <" + columns[8] + ">"))
}).ToList();
xmls.ForEach(a => a.XELEM.Save(@"C:\" + a.XFILENAME + ".xml"));
或使用字典:
var xmls2 = (from str in lines
let columns = str.Split(',')
select new KeyValuePair<string, XElement>(
columns[1] + "_" + columns[4],
new XElement("recording_info",
new XElement("recorded_accound_id", columns[1]),//Line01
new XElement("date_created_ts", String.Format("{0:####-##-## ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))), //date
new XElement("recorded_cid", columns[9]),//1
new XElement("recording_tag", columns[1]),//Line01
new XElement("from_caller_id", columns[10] + " <" + columns[8] + ">"))
)).ToDictionary(a => a.Key, a => a.Value);
foreach (var o in xmls2)
{
o.Value.Save(@"C:\" + o.Key + ".xml");
}