As I mentioned in my previous post about the gl-exportcontenttypes command I need to be able to quickly and easily get the CAML necessary to recreate site columns in a Feature. To do this I created a quick and dirty command called gl-exportsitecolumns. The code for this is extremely simple – I just get the SPField objects of interest based on the parameters passed in and dump out the SchemaXml property – that’s it:

 1string url = Params["url"].Value;
 2string fieldTitle = Params["fielddisplayname"].Value;
 3string fieldName = Params["fieldinternalname"].Value;
 4string groupName = Params["group"].Value;
 5bool useTitle = Params["fielddisplayname"].UserTypedIn;
 6bool useName = Params["fieldinternalname"].UserTypedIn;
 7bool useGroup = Params["group"].UserTypedIn;
 8bool all = !(useTitle || useName || useGroup);
 9 
10StringBuilder sb = new StringBuilder();
11XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
12xmlWriter.Formatting = Formatting.Indented;
13 
14try
15{
16 xmlWriter.WriteStartElement("Elements");
17 
18 // Get the source content type and fields.
19 using (SPSite site = new SPSite(url))
20 {
21  using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
22  {
23   SPFieldCollection fields = web.Fields;
24   foreach (SPField field in fields)
25   {
26    if (all ||
27     (useGroup && groupName.ToLowerInvariant() == field.Group.ToLowerInvariant()) ||
28     (useName && fieldName.ToLowerInvariant() == field.InternalName.ToLowerInvariant()) ||
29     (useTitle && fieldTitle.ToLowerInvariant() == field.Title.ToLowerInvariant()))
30    {
31     xmlWriter.WriteString("\r\n");
32     xmlWriter.WriteRaw(field.SchemaXml);
33    }
34   }
35  }
36 }
37 
38 xmlWriter.WriteString("\r\n");
39 xmlWriter.WriteEndElement(); // Elements
40}
41finally
42{
43 xmlWriter.Flush();
44 xmlWriter.Close();
45}
46File.WriteAllText(Params["outputfile"].Value, sb.ToString());

The syntax of the command can be seen below:

C:\>stsadm -help gl-exportsitecolumns

stsadm -o gl-exportsitecolumns


Exports one or more site fields (columns) to a file.

Parameters:
        -url <url>
        {[-fielddisplayname <field display name> / -fieldinternalname <field internal name>]
         [-group <site column group name to filter results by>]}
        -outputfile <file to output field schema to>

Here’s an example of how to dump the XML for all the site columns in a particular group:

  stsadm -o gl-exportsitecolumns -url "http://intranet" -outputfile c:\fields.xml -group "Custom Site Columns"