Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

Publishing to a WordPress Blog via XML-RPC (Part 4)

Please refer to this post for some background.

When you’re sending requests to the server, you have to build text in XML. There are a few ways to do this in C#. One way is to use classes that were designed for this in the .NET Framework. However, I decided not to use these because they can be confusing and because they are specific to the .NET Framework. Instead I decided to build the XML using the StringBuilder class, which allows you to efficiently create long string objects. Some people may think this is a hack, but I have found that it reduces the amount of code that is needed. It especially made sense in this scenario in which the XML structure is pretty consistent for the various types of requests. And as I mentioned, doing it this way should make it easier to translate this code into other programming languages.

The following class is designed for doing part of this work. It takes values that the user specifies and builds “struct” XML, which is more complicated XML when you have to pass more than single values to the server.

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Piccolo.Common
{
	public class WordPressXmlBuilder
	{
		public static string BuildStructArray(params KeyValuePairs[] pairArray)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("<array>\n<data>\n");
 
			foreach (KeyValuePairs pairs in pairArray)
				sb.Append(BuildStruct(pairs));
 
			sb.Append("</data>\n</array>\n");
			return sb.ToString();
		}
 
		public static string BuildStruct(WordPressBlogPost post)
		{
			KeyValuePairs structVals = new KeyValuePairs();
			structVals.Add("description", post.Text);
			structVals.Add("title", post.Title);
			return BuildStruct(structVals);
		}
 
		public static string BuildStruct(KeyValuePairs structVals)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("<struct>\n");
 
			foreach (KeyValuePair<string, string> pair in structVals)
				sb.AppendFormat("<member><name>{0}</name><value>{1}</value></member>\n", pair.Key, pair.Value);
 
			sb.Append("</struct>\n");
			return sb.ToString();
		}
	}
}

Leave a Reply