tags:

views:

159

answers:

3

For my web service component, I need to generate a relatively large XML (~500 lines) according to many factors. I am facing a few different choices here: 1. StringBuilder 2. XmlWriter class 3. C# object with serialization???

Which one should I use. Is there any other ways that I am not aware of?

A: 

I generate an RSS feed very simply using LINQ to XML. It's the nicest XML API I know of, to be honest.

I have a a couple of extension methods which I use to make it even easier - it converts from an anonymous type to either elements or attributes:

  public static IEnumerable<XElement> AsXElements(this object source)
  {
      foreach (PropertyInfo prop in source.GetType().GetProperties())
      {
          object value = prop.GetValue(source, null);
          yield return new XElement(prop.Name.Replace("_", "-"), value);
      }
  }

  public static IEnumerable<XAttribute> AsXAttributes(this object source)
  {
      foreach (PropertyInfo prop in source.GetType().GetProperties())
      {
          object value = prop.GetValue(source, null);
          yield return new XAttribute(prop.Name.Replace("_", "-"), value ?? "");
      }
  }

That may not be at all appropriate for you, but I find it really handy. Of course, this assumes you're using .NET 3.5...

Jon Skeet
+1  A: 

If you populate the XML with data from database, you can generate the whole XML by using SQL query and create a class with a property holds the XML blob. The property type can be XElement. This is the easiest I can think of.

codemeit
A: 

Need more info, but I would not use Object serialization. It's quite rigid and hides too much of the implementation. Especially when consumed by somebody other than your own application. I would also not use a StringBuilder because all of a sudden you are handling the escaping of content and doing all the hard and error-prone work yourself.

For low level stuff, XmlWriter is a good way to go. If you're Linqing, then the XElement stuff is pretty nice.

Keltex