Monday, July 11, 2011

Create XML string using XmlTextWriter class

The Basics of the XmlTextWriter Class
The XmlTextWriter class contains a number of methods that are useful for starting and completing an XML document and for adding elements and attributes to the XML document. The most important methods are:

WriteStartDocument() - you should call this method to start creating an XML document. This will create the first line in the XML document, specifying that the file is an XML document and its encoding.


WriteStartElement(string) - this method creates a new element in the XML document with the name specified by the string input parameter. (You can also specify a namespace as a second, optional string parameter.)


WriteElementString(name, text_value) - If you want to create an XML element with nothing but text content (i.e., no nested elements), you can use this method.

WriteAttributeString(name, value) - this method writes an attribute name and value to the current element.


WriteEndElement() - this method closes off the element created in the WriteStartElement(string) method call.

WriteEndDocument() - this method completes the writing of the XML document.

Example:

<root>
<Employee>
<EmployeeID>
6
</EmployeeID>
<Name>
Pa Ji
</Name>


</Employee>
</root>

private string GenerateXmlString()
{
StringBuilder xmlBuilder = new StringBuilder( 1000 );
TextWriter xmlWriter = new StringWriter( xmlBuilder );
XmlTextWriter xmlMessage = new XmlTextWriter( xmlWriter );
xmlMessage.WriteStartElement( "root" );
xmlMessage.WriteStartElement( "Employee" );
xmlMessage.WriteStartElement( "EmployeeID" );

xmlMessage.WriteString("6");

xmlMessage.WriteEndElement( );
xmlMessage.WriteStartElement( "Name" );
xmlMessage.WriteString( "Pa Ji");

xmlMessage.WriteEndElement() ;

xmlMessage.WriteEndElement( ); // </Employee>

xmlMessage.WriteEndElement( ); // </Root>
return xmlBuilder.ToString( );
}

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...