3

我想创建具有以下结构的 xml 文档

<ServerFp Command="Cashed">
    <Cashed Value="199.99"/>
</ServerFp>

所以我尝试这样:

XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
            using (var writer = XmlWriter.Create(filename, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("ServerFp");
                writer.WriteAttributeString("Command", "Cashed");

            }

到目前为止这很好吗?如何结束这个文件?带节点<Cashed Value="199.99"/>

4

5 回答 5

4

我会尝试这样做:

创建一个新的 XmlDocument:

XmlDocument doc = new XmlDocument();

创建要插入的节点

XmlNode node1 = doc.CreateElement("node1")

附加你的元素

doc.AppendChild(node1 );

保存文档

doc.Save("result.xml");
于 2013-08-13T10:02:06.537 回答
3

为什么不只是LINQ to XML

XElement ServerFp = new XElement("ServerFp",
    new XAttribute("Command", "Cached"),
    new XElement("CachedValue", "199.99")
);
Console.WriteLine(ServerFp.ToString());

输出

<ServerFp Command="Cached">
  <CachedValue>199.99</CachedValue>
</ServerFp>
于 2013-08-13T10:05:47.290 回答
2

试试这个LINQ To XML

 XElement result = new XElement("ServerFp", new XAttribute("Command", "Cashed"),
                   new XElement("Cashed", new XAttribute("Value", "199.99"))
                   );

输出

<ServerFp Command="Cashed">
  <Cashed Value="199.99" />
</ServerFp>
于 2013-08-13T10:36:19.277 回答
1

这就是您可以使用的方法XmlWriter

writer.WriteStartDocument();
writer.WriteStartElement("ServerFp");
writer.WriteAttributeString("Command", "Cashed");
writer.WriteStartElement("Cashed");
writer.WriteAttributeString("Value", "199.99");
writer.WriteEndElement();
writer.WriteEndElement();

或者您可以使用XDocument

XDocument doc = new XDocument(new XElement("ServerFp", new XAttribute("Command", "Cashed"), 
    new XElement("Cashed", new XAttribute("Value", "199.99"))));

doc.Save(filePath);
于 2013-08-13T10:04:03.140 回答
0

试试这个(我不确定,但你可以知道)

XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (var writer = XmlWriter.Create(filename, settings))
{
     writer.WriteStartDocument();
     writer.WriteStartElement("ServerFp");
     writer.WriteAttributeString("Command", "Cashed");

     writer.WriteEndElement(); // I think this will close your <Cashed Value="199.99"/>
     writer.WriteEndElement(); // I think this will close your 
}
于 2013-08-13T10:02:29.940 回答