使用C#,我正在尝试编写一个XML文件,该文件将包含节点(从SQLite DB读取的数据)的未知数(编译时未知,可以在搜索SQLite DB后弄清楚该数字)。 ),将其命名为相同的(设置)。设置节点的数量可能为数千。
<Set>
<Setting Name="Ted" empID="60000004">Ted</Setting>
<Setting Name="Bill" empID="60000007">Bill</Setting>
<Setting Name="Steve empID="60000010">Steve</Setting>
<Setting Name="Sara" empID="60000013">Sara</Setting>
<Setting Name="Tom" empID="60000016">Tom</Setting>
<Setting Name="Sam" empID="60000019">Sam</Setting>
<Setting Name="Alex" empID="60000022">Alex</Setting>
<Setting Name="Sue" empID="60000025">Sue</Setting>
<Setting Name="Jill" empID="60000028">Jill</Setting>
<Setting Name="Mya" empID="60000031">Mya</Setting>
</Set>
这是我正在使用的代码,但失败了:
XDocument doc = new XDocument(new XElement("Set"));
while (reader.Read())
{
doc.Element("Set").Add(new XElement("Setting", _Name));
doc.Element("Set").Element("Setting").Add(new XAttribute("empID", _ID));
}
doc.Save(_sOutputFolderName + "Employee_Information.xml");
答案 0 :(得分:0)
您试图在每个循环中将XAttribute添加到相同的XElement。应该是这样的:
XDocument doc = new XDocument(new XElement("Set"));
for (int i = 0; i < 10; i++)
{
var _Name = "n" + i ;
var _ID = "12" + i;
var setting = new XElement("Setting", _Name );
setting.Add(new XAttribute("empID", _ID));
doc.Element("Set").Add(setting);
}
Console.WriteLine(doc.ToString());
答案 1 :(得分:0)
尝试一下...
XDocument doc = new XDocument(new XElement("Set"));
while (reader.Read()) {
var setting = new XElement("Setting", "the name");
setting.Add(new XAttribute("empID", "the id"));
doc.Root.Add(setting);
}