Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StyleCop happy creation of Xml using XDocument / XElement / XAttribute

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?

like image 442
Tallek Avatar asked Nov 05 '22 11:11

Tallek


1 Answers

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.

like image 68
Task Avatar answered Nov 14 '22 23:11

Task