如何用c#编写XML

本文关键字:XML 编写 何用 | 更新日期: 2023-09-27 18:07:17

<Account nr="401" name="Wasser/Abwasser" income="0.00" expenditure="1,310.74" saldo="-1,310.74" resultText="Es wurden ausgegeben">
    <Accounting date="15.02." refNr="....." description="I/2013"  income="" expenditure="1,310.74" vat="10%" pretax="131.07"/>
  </Account>

我可以使用xmltextwwriter,但不知道如何继续使用nr,name.....

myXmlTextWriter.WriteStartElement("Account");.....
myXmlTextWriter.WriteElementString("Accounting",......

thx

如何用c#编写XML

尝试使用XElement结束XAttribute类。它们是LINQ to XML的一部分,它们使处理XML变得更加容易。

var xml = new XElement("Account",
              new XAttribute("nr", 401),
              new XAttribute("name", "Wasser/Abwasser"),
              new XElement("Accounting",
                  new XAttribute("date", "15.02."),
                  new XAttribute("refNr", "...")));

返回.ToString():

<Account nr="401" name="Wasser/Abwasser">
  <Accounting date="15.02." refNr="..." />
</Account>

按照模式填充其余的属性,您将得到您想要的。

您将需要发出WriteAttributeString:

myXmlTextWriter.WriteAttributeString(null, "nr", null, "401");
myXmlTextWriter.WriteEndElement();

并在WriteStartElement之后执行。

你也可以使用这个重载:

myXmlTextWriter.WriteAttributeString("nr", "401");

,当然对所有其他属性复制。对于子节点也是一样的

使用LINQ to XML可以非常简单地做到这一点:

var document = new XDocument( 
                   new XElement("Account",
                       new XAttribute("nr", 401),
                          ...));
document.WriteTo(myXmlTextWriter);