0

我有以下 XML:

<Account>
    <nr>6134</nr>
    <name>Summ</name>
    <Accounting>
      <income>200</income>
    </Accounting>
    <summincome>200</summincome>
</Account> 

我尝试过但没有成功:

myXmlTextWriter2.WriteStartElement("Account");
myXmlTextWriter2.WriteAttributeString("nr", AccountNumber.ToString());
myXmlTextWriter2.WriteAttributeString("name", Name);

double summ=0;
foreach (AccountRecord ar in kp)
{
 myXmlTextWriter2.WriteStartElement("Accounting");
 myXmlTextWriter2.WriteAttributeString("income", ar.Amount.ToString());
 myXmlTextWriter2.WriteEndElement();
 summ += ar.Amount;
 }

myXmlTextWriter2.WriteAttributeString("summincome", summ.ToString());
myXmlTextWriter2.WriteEndElement();

如您所见,我输入了一个 foreach 循环来计算总和并将其值分配给“summincome”。提前谢谢你的小费

4

2 回答 2

1

试试这个

using (XmlWriter writer = XmlWriter.Create("accounts.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Account");
    writer.WriteElementString("nr", AccountNumber.ToString());
    writer.WriteElementString("name", Name);

    double summ=0;
    foreach (AccountRecord ar in kp)
    {
    writer.WriteStartElement("Accounting");
    writer.WriteElementString("income", ar.Amount.ToString());
    writer.WriteEndElement();
    summ += ar.Amount;
    }
    writer.WriteElementString("summincome", summ.ToString())
    writer.WriteEndElement();
    writer.WriteEndDocument();
}
于 2013-04-04T12:36:03.640 回答
1

它们不是属性而是元素

myXmlTextWriter2.WriteStartElement("Account");
myXmlTextWriter2.WriteAttributeString("nr", AccountNumber.ToString());
myXmlTextWriter2.WriteAttributeString("name", Name);

double summ=0;
foreach (AccountRecord ar in kp)
{
 myXmlTextWriter2.WriteStartElement("Accounting");
 myXmlTextWriter2.WriteElementString("income", ar.Amount.ToString());
 myXmlTextWriter2.WriteEndElement();
 summ += ar.Amount;
 }

myXmlTextWriter2.WriteElementString("summincome", summ.ToString());
myXmlTextWriter2.WriteEndElement();
于 2013-04-04T12:39:22.663 回答