使用LINQ编写XML文件时使用for循环 [英] Use for loop when writing a XML file with LINQ
本文介绍了使用LINQ编写XML文件时使用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须将数据保存到XML文件,该数据存储在4个数组和2个int中.我必须在每个数组中使用相同的元素(例如candTur1[0]
和votTur1[0]
)
I must save data to an XML file, the data is stored in 4 arrays and 2 int. I must use the same element from each array ( Ex candTur1[0]
with votTur1[0]
)
我尝试使用此代码:
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("alegeri",
new XElement("tur",
new XElement("nrtur", 1),
for (int i = 0; i < candTur1.Length; i++)
{
new XElement("candidat",
new XElement("nume", candTur1[i]),
new XElement("voturi",votTur1[i] ),
new XElement("procent",((votTur1[i] * 100) / votanti)) );
};
);
);
document.Save("People.xml");
所有数组都具有相同的长度,并且XML应该看起来像:
All arrays have the same length and the XML should look like :
<?xml version="1.0" encoding="utf-8" ?>
<alegeri>
<tur>
<nrtur>1</nrtur>
<alegatori>2341</alegatori>
<candidat>
<nume>Ion</nume>
<voturi>50</voturi>
<procentaj>50</procentaj>
</candidat>
</tur>
<tur>
<nrtur>2</nrtur>
<alegatori>2341</alegatori>
<candidat>
<nume>Ion</nume>
<voturi>50</voturi>
<procentaj>50</procentaj>
</candidat>
</tur>
</alegeri>
谢谢!
推荐答案
您可以执行以下操作:
XDocument document = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("alegeri",
Enumerable.Range(1,2).Select(i =>
new XElement("tur",
new XElement("nrtur", i),
candTur1.Select((s, index) =>
new XElement("candidat",
new XElement("nume", candTur1[index]),
new XElement("voturi",votTur1[index] ),
new XElement("procent",((votTur1[index] * 100) / votanti)) ))))));
我不知道数组的外观,但是此代码假定所有数组的长度相同.
I don't know how the arrays looks like, but this code presumes that all arrays are of the same length.
这篇关于使用LINQ编写XML文件时使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文