Now that the XML declaration is written, it's time to start writing some real XML data. The most important node is the XML element. Elements can be written piece by piece or all at once. Writing an element piece by piece is necessary when the element needs to contain attributes or child nodes. The XmlTextReader provides WriteStartElement and WriteEndElement to support this functionality. Calling WriteStartElement will write the specified start tag and associate it with an optional namespace and prefix. After the start tag is written, you can then write attributes on the element. You can also write child nodes. But you can no longer write an attribute on an element after a child node has been written. Listing 10.23 demonstrates how to use WriteElementString and WriteEndElement to write an empty element.
Listing 10.23C# XmlTextWriter writer = new XmlTextWriter("startelem.xml", Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteEndElement(); writer.Close(); VB Dim writer As New XmlTextWriter("startelem.xml", Encoding.UTF8) writer.Formatting = Formatting.Indented writer.WriteStartDocument() writer.WriteStartElement("root") writer.WriteEndElement() writer.Close() Output <?xml version="1.0" encoding="utf-8"?> <root /> An element that contains only text can be written by calling one, single API method, WriteElementString , which will write out the start tag, the text content, and the end tag. Unfortunately, attributes other than namespace declarations cannot be written. Listing 10.24 demonstrates how to use WriteElementString . Listing 10.24C# XmlTextWriter writer = new XmlTextWriter("elementstring.xml", Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartElement("StockQuote", "http://fakequote.com"); writer.WriteElementString ("Symbol", "http://fakequote.com", "MSFT"); writer.WriteElementString("Value", "http://fakequote.com", XmlConvert.ToString(123.32)); writer.WriteEndElement(); writer.Close(); VB Dim writer As New XmlTextWriter("elementstring.xml", Encoding.UTF8) writer.Formatting = Formatting.Indented writer.WriteStartElement("StockQuote", "http://fakequote.com") writer.WriteElementString _ ("Symbol", "http://fakequote.com", "MSFT") writer.WriteElementString("Value", _ "http://fakequote.com", _ XmlConvert.ToString(123.32)) writer.WriteEndElement() writer.Close() Output <StockQuote xmlns="http://fakequote.com"> <Symbol>MSFT</Symbol> <Value>123.32</Value> </StockQuote> |