Share via


Writing Elements

The WriteElementString, WriteStartElement, and WriteNode methods can be used to write element nodes.

WriteElementString

The WriteElementString is used to write an entire element node, including a string value. The following code writes out the <price>19.95</price> XML string.

writer.WriteElementString("price", "19.95")
writer.WriteElementString("price", "19.95");

WriteStartElement

WriteStartElement is a more advanced version of the WriteElementString method. It allows you to write the element value using multiple method calls. For example, you can call WriteValue to write a typed value, WriteCharEntity to write a character entity, WriteAttributeString to write an attribute, or you can write a child element.

The element is closed by calling the WriteEndElement or WriteFullEndElement method.

The following example writes two nested elements.

writer.WriteStartElement("bk", "book", "urn:books")
writer.WriteAttributeString("genre", "urn:books", "mystery")
writer.WriteElementString("price", "19.95")
writer.WriteEndElement()
writer.WriteStartElement("bk", "book", "urn:books");
writer.WriteAttributeString("genre", "urn:books", "mystery");
writer.WriteElementString("price", "19.95");
writer.WriteEndElement();

The following XML node is written.

<bk:book bk:genre="mystery" xmlns:bk="urn:books">
  <price>19.95</price>
</bk:book>

WriteNode

The WriteNode method allows you to copy an entire element node found at the current position of the supplied XmlReader or XPathNavigator object. When called, it copies everything from the source object to the XmlWriter instance.

' Create a reader and position it on the book node. 
Dim reader As XmlReader = XmlReader.Create("books.xml")
reader.ReadToFollowing("book")

' Write out the book node. 
Dim writer As XmlWriter = XmlWriter.Create("newBook.xml")
writer.WriteNode(reader, True)
writer.Flush()
// Create a reader and position it on the book node.
XmlReader reader = XmlReader.Create("books.xml");
reader.ReadToFollowing("book");

// Write out the book node.
XmlWriter writer = XmlWriter.Create("newBook.xml");
writer.WriteNode(reader, true);
writer.Flush();

The following XML file is created.

<?xml version="1.0" encoding="utf-8"?>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
  <title>The Autobiography of Benjamin Franklin</title>
  <author>
    <first-name>Benjamin</first-name>
    <last-name>Franklin</last-name>
  </author>
  <price>8.99</price>
</book>

See Also

Other Resources

Writing XML with the XmlWriter