Reputation: 3515
I want to create xml document with following structure
<ServerFp Command="Cashed">
<Cashed Value="199.99"/>
</ServerFp>
So I tried like this :
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (var writer = XmlWriter.Create(filename, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("ServerFp");
writer.WriteAttributeString("Command", "Cashed");
}
Is this good so far and how to end this file? with node <Cashed Value="199.99"/>
Upvotes: 3
Views: 144
Reputation: 1291
Try this LINQ To XML
XElement result = new XElement("ServerFp", new XAttribute("Command", "Cashed"),
new XElement("Cashed", new XAttribute("Value", "199.99"))
);
Output
<ServerFp Command="Cashed">
<Cashed Value="199.99" />
</ServerFp>
Upvotes: 2
Reputation: 3660
why not just LINQ to XML?
XElement ServerFp = new XElement("ServerFp",
new XAttribute("Command", "Cached"),
new XElement("CachedValue", "199.99")
);
Console.WriteLine(ServerFp.ToString());
outputting
<ServerFp Command="Cached">
<CachedValue>199.99</CachedValue>
</ServerFp>
Upvotes: 3
Reputation: 63065
this is how you can do it by using XmlWriter
writer.WriteStartDocument();
writer.WriteStartElement("ServerFp");
writer.WriteAttributeString("Command", "Cashed");
writer.WriteStartElement("Cashed");
writer.WriteAttributeString("Value", "199.99");
writer.WriteEndElement();
writer.WriteEndElement();
Or you can do the same using XDocument
XDocument doc = new XDocument(new XElement("ServerFp", new XAttribute("Command", "Cashed"),
new XElement("Cashed", new XAttribute("Value", "199.99"))));
doc.Save(filePath);
Upvotes: 1
Reputation: 10010
Try this (I am not sure but you can get an idea)
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
}
Upvotes: 0
Reputation: 126
I would try doing it like this:
create a new XmlDocument:
XmlDocument doc = new XmlDocument();
create your nodes you want to insert
XmlNode node1 = doc.CreateElement("node1")
append your element
doc.AppendChild(node1 );
save the document
doc.Save("result.xml");
Upvotes: 4