views:

159

answers:

1

I like to create xml using the following formatting:

XDocument xml = new XDocument(
   new XElement("Root",
      new XElement("A",
         new XAttribute("X", xValue),
         new XAttribute("Y", yValue)),
      new XElement("B",
         new XAttribute("Z", zValue)),
      new XElement("C")));

It seems easy to read and kinda flows like a tabbed XML document (in my opinion). StyleCop is very unhappy with the formatting though. I get a lot of these errors:

SA1116: If the method parameters are on separate lines, the first parameter must begin on the line beneath the name of the method.

SA1118: The parameter spans multiple lines. If the parameter is short, place the entire parameter on a single line. Otherwise, save the contents of the parameter in a temporary variable and pass the temporary variable as a parameter.

What can i do to keep StyleCop happy and the code readable? I know i can disable the StyleCop rules, but the team would like to keep those rules for all the non XML creation code. I can selectively suppress the rule in every method that creates XML in this way, but that seems like a pain and gets to be ugly. Any suggestions?

+2  A: 

Yes, I would suggest the following:

  • Create 'default resources' for your project (right-click the project, Properties, Resourced)
  • Create a new string resource there, set the Name as DefaultXmlDoc or something
  • Set the value as the following text:
    <Root>
    <A X="1" Y="2" />
    <B Z="3" />
    <C />
    </Root>
  • Change your program to the following one-liner:
    XDocument xml = XDocument.Parse( Properties.Resources.DefaultXmlDoc );

I believe this accomplishes all your goals.

Task
Well, that sounds like it would work, i guess i should have been a bit more clear though. I create xml in many places throughout the code and almost always, there is dynamic data in it. If i used a resource string, i would end up needing to do a bunch of replacements of placeholder values with the real values. At that point, the cure might be worse than the disease...
Tallek
I guarantee, it does work. The way to handle the dynamic replacement values is by placing a {0} in the resource string and then wrapping the resource string fetching with a small routine that does a String.Format on the resource string with additional arguments. I've used this method myself and (with the correct implementation) it's been absolutely wonderful to work with. All my large hardcoded strings with a couple dynamic values inside them are completely handled by a small 'string pre-processing' system. If there's a better way, I'd love to know it.
Task