创建xml文件,基础知识

时间:2013-08-13 09:57:52

标签: c# .net

我想用以下结构创建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"/>

5 个答案:

答案 0 :(得分:4)

我会尝试这样做:

创建一个新的XmlDocument:

XmlDocument doc = new XmlDocument();

创建要插入的节点

XmlNode node1 = doc.CreateElement("node1")

追加你的元素

doc.AppendChild(node1 );

保存文件

doc.Save("result.xml");

答案 1 :(得分: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>

答案 2 :(得分: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>

答案 3 :(得分: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);

答案 4 :(得分: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 
}