简体   繁体   中英

What's the Best way to Generate a Dynamic XML for Web Service?

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?

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.

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 aa 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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM