How to add nodes with the same name in a loop?
I'm trying to create the following XML file开发者_如何学C:
<Clientes>
<Cliente>
<Name>sfsdfsd</Name>
<Phone>
</Phone>
<Matriculas>
<Matricula>
<Nr>567856786</Nr>
<Marca>86786</Marca>
<Modelo>8678678</Modelo>
</Matricula>
<Matricula>
<Nr>u56u5u</Nr>
<Marca>4564b5</Marca>
<Modelo>b456b</Modelo>
</Matricula>
</Matriculas>
</Cliente>
</Clientes>
I have several clientes stored in a List and each of them may have more then one Matricula, stored in a List
i have the following code:
foreach (Cliente c in cli)
{
XmlNode xCliente = xDoc.CreateElement("Cliente");
XmlNode xName = xDoc.CreateElement("Name");
XmlNode xPhone = xDoc.CreateElement("Phone");
XmlNode xMatriculas = xDoc.CreateElement("Matriculas");
XmlNode xMatricula = xDoc.CreateElement("Matricula");
XmlNode xNr = xDoc.CreateElement("Nr");
XmlNode xMarca = xDoc.CreateElement("Marca");
XmlNode xModelo = xDoc.CreateElement("Modelo");
xName.InnerText = c.Name;
xPhone.InnerText = c.Phone;
xCliente.AppendChild(xName);
xCliente.AppendChild(xPhone);
foreach (Matricula m in c.matricula)
{
xNr.InnerText = m.nr;
xMarca.InnerText = m.marca;
xModelo.InnerText = m.modelo;
xMatricula.AppendChild(xNr);
xMatricula.AppendChild(xMarca);
xMatricula.AppendChild(xModelo);
xMatriculas.AppendChild(xMatricula);
}
xCliente.AppendChild(xMatriculas);
xDoc.DocumentElement.AppendChild(xCliente);
}
i can add several Cliente to the root, but only the last Matricula in Matriculas is added.
Move
XmlNode xMatricula = xDoc.CreateElement("Matricula");
XmlNode xNr = xDoc.CreateElement("Nr");
XmlNode xMarca = xDoc.CreateElement("Marca");
XmlNode xModelo = xDoc.CreateElement("Modelo");
inside the inner for loop.
You are reusing the exact same node, you need to create a new node every time you want a new node in your document.
精彩评论