Unit-4
Unit-4
xmlDoc.Save("newbooks.xml");
}
}
Using the XmlWriter Class:
The XmlWriter class is another way to write XML files in C#. It provides a
more efficient way to create large XML files because it writes the XML data
directly to a file, rather than creating an entire XML document in memory.
using System; using
System.Xml; class
Program
{
static void Main(string[] args)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("newbooks.xml", settings))
{
writer.WriteStartElement("books");
writer.WriteStartElement("book");
writer.WriteAttributeString("title", "Programming C#");
writer.WriteAttributeString("author", "John Doe");
writer.WriteAttributeString("publisher", "O'Reilly");
writer.WriteAttributeString("price", "29.99");
writer.WriteEndElement(); writer.WriteEndElement();
}
}
}
In this example, we create an instance of the XmlWriter class and pass the
name of the XML file and an XmlWriterSettings object to the Create method.
We then use the WriteStartElement method to create the "books" element and
the WriteAttributeString method to create the attributes for the "book"
element. Finally, we use the WriteEndElement method to close the "book" and
"books" elements.