a developer's notes – a semi-technical web development BLOG

May 4, 2012

Creating and reading an XML String in C#

Filed under: C# — Duy Nguyen @ 2:11 pm
Tags: , , , ,

This is how to create an XML String with xmlTextWriter in .NET 4.0:

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

xmlTextWriter.WriteStartElement("MYELEMENT");
xmlTextWriter.WriteAttributeString("my_attribute", "myValue");
xmlTextWriter.WriteElementString("ID", "myId");
xmlTextWriter.WriteEndElement();  //closing xml tag for ID
xmlTextWriter.WriteEndElement(); //closing xml tag for MYELEMENT

xmlTextWriter.Close();

return stringWriter.ToString();

Your XML:

<MYELEMENT my_attribute="myValue">
<ID>myId</ID>
<MYELEMENT>

Reading in XML with XmlTextReader

<filter>
	<sort by="teamName" direction="asc"/>
	<expressions>
		<expression type="nvarchar" field="teamName" operator="like" value="001"/>
	</expressions>
</filter>

private static void ReadXmlWithXmlTextReader(string xml)
{
	XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml));
	string sortFieldBy = string.Empty;
	string sortDirection = string.Empty;
	string filtertype = string.Empty;
	string filterField = string.Empty;
	string filterOperator = string.Empty;
	string filterValue = string.Empty;

	//  Loop over the XML file
	while (xmlTextReader.Read())
	{
		if (xmlTextReader.NodeType == XmlNodeType.Element)
		{
			if (xmlTextReader.Name == "sort")
			{
				sortFieldBy = xmlTextReader.GetAttribute("by");
				sortDirection = xmlTextReader.GetAttribute("direction");
			}

			if(xmlTextReader.Name == "expression")
			{
				filtertype = xmlTextReader.GetAttribute("type");
				filterField = xmlTextReader.GetAttribute("field");
				filterOperator = xmlTextReader.GetAttribute("operator");
				filterValue = xmlTextReader.GetAttribute("value");
			}
		}
	}
	xmlTextReader.Close();
}

In .NET 3.5: XDocument

XDocument doc = new XDocument(
    new XElement("root",
                 new XAttribute("name", "value"),
                 new XElement("child", "text node")));

From MSDN, “There are not many scenarios that require you to create an XDocument. Instead, you can usually create your XML trees with an XElement root node. Unless you have a specific requirement to create a document (for example, because you have to create processing instructions and comments at the top level, or you have to support document types), it is often more convenient to use XElement as your root node.”
Check this out.

XElement xml = new XElement("contacts",
                    new XElement("contact", 
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Barry"),
                        new XElement("lastName", "Gottshall")
                    ),
                    new XElement("contact", 
                        new XAttribute("contactId", "3"),
                        new XElement("firstName", "Armando"),
                        new XElement("lastName", "Valdes")
                    )
                );
Console.WriteLine(xml);

Your XML:

<contacts>
  <contact contactId="2">
    <firstName>Barry</firstName>
    <lastName>Gottshall</lastName>
  </contact>
  <contact contactId="3">
    <firstName>Armando</firstName>
    <lastName>Valdes</lastName>
  </contact>
</contacts>

.NET version 3.0 or lower: XmlDocument

static private void BuildXmlForProc(List<int> mainIds)
{
	//ELEMENT CONSTANTS
	const string XML_DOCUMENT_ROOT_ELEMENT = "mids";
	const string MAIN_ID_ELEMENT = "mid";

	XmlDocument xmlDocument = new XmlDocument();
	XmlElement root = xmlDocument.CreateElement(XML_DOCUMENT_ROOT_ELEMENT);
	xmlDocument.AppendChild(root);

	foreach (var id in mainIds)
	{
		XmlElement mainId = xmlDocument.CreateElement(MAIN_ID_ELEMENT);
		mainId.InnerText = "4033";
		root.AppendChild(mainId);    
	}
}

<mids>
	<mid>4033</mid>
</mids>

You can always use the string builder class. http://www.devx.com/tips/Tip/41390

var stringBuilder = new StringBuilder();
stringBuilder.Append("<filter>");
stringBuilder.Append("<expressions>");

const string fieldType = "type=\"nvarchar\"";
const string filterOperator = "operator=\"LIKE\"";

if (filterParams != null)
{
	foreach (var filterParam in filterParams)
	{
		stringBuilder.Append("<expression " + fieldType +  " field=\"" + filterParam.Field + "\" " + filterOperator +  " value=\"" + filterParam.Data.Value + "\" />");
	}
}

stringBuilder.Append("</expressions>");
stringBuilder.Append("</filter>");

return stringBuilder.ToString();
<filter>
	<sort by="teamName" direction="asc"/>
	<expressions>
		<expression type="nvarchar" field="teamName" operator="like" value="001"/>
	</expressions>
</filter>
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: