2013-04-04 61 views
0

我有以下XML:如何使用XmlTextWriter元素?

<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循環計算SUMM和分配給它的值改爲「summincome 」。 THX提前爲您的竅門

+0

'name'和'summincome'不是屬性。 – 2013-04-04 12:31:25

+0

你必須使用TextWriter嗎? XElement等人對此更容易。 – 2013-04-04 12:31:58

回答

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(); 
+0

是的,那是我的錯誤..thx – Georg 2013-04-04 12:51:17

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(); 
} 
+0

This works too too ... thx – Georg 2013-04-04 12:51:42

相關問題