Here is the code that you can reuse to read the complete managed metadata store or taxonomy in SharePoint for a specific site collection.
Below code writes the metadata to a xml file following a very basic schema also presents it on console in a formatted style.
For basic understanding, the classes or the taxonomy hierarchy(new in SharePoint) is like below
Taxonomy Session
|
Term Store
|
Group
|
TermSet
|
Term
Microsoft.SharePoint.Taxonomy is the dll that's used here to play around with SharePoint taxonomies.
namespace MetaDataReader
{
class Program
{
static string fmt = "---------"; // used for formatting the hierarchy while displaying on console
static XmlTextWriter writer = new XmlTextWriter("metadataStore.xml", null);
public static void Main(string[] args)
{
try
{
SPSite site = new SPSite("http://mywebappurl");
TaxonomySession txSesssion = new TaxonomySession(site);
writer.WriteStartDocument();
foreach (TermStore store in txSesssion.TermStores)
{
Console.WriteLine("TermSTORE : " + store.Name);
writer.WriteStartElement("TermStore");
writer.WriteStartElement("Name");
writer.WriteString(store.Name);
writer.WriteEndElement();
foreach (Group g in store.Groups)
{
Console.WriteLine("...TermGROUP : " + g.Name);
writer.WriteStartElement("TermGroup");
writer.WriteStartElement("Name");
writer.WriteString(g.Name);
writer.WriteEndElement();
foreach (TermSet tSet in g.TermSets)
{
Console.WriteLine("......TermSET : " + tSet.Name);
writer.WriteStartElement("TermSet");
writer.WriteStartElement("Name");
writer.WriteString(tSet.Name);
writer.WriteEndElement();
foreach (Term t in tSet.Terms)
{
Console.WriteLine(fmt + "TERM :" + t.Name);
writer.WriteStartElement("Term");
writer.WriteStartElement("Name");
writer.WriteString(t.Name);
writer.WriteEndElement();
getTermsRecursive(t);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndDocument();
writer.Close();
}
catch (Exception ex)
{//Do not swallow ;}
}
public static void getTermsRecursive(Term t)
{
if (t.Terms.Count > 0)
{
fmt += "---";
foreach (Term sTerm in t.Terms)
{
Console.WriteLine(fmt + "TERM :" + sTerm.Name );
writer.WriteStartElement("Term");
writer.WriteStartElement("Name");
writer.WriteString(sTerm.Name);
writer.WriteEndElement();
getTermsRecursive(sTerm);
writer.WriteEndElement();
}
}
else
{
fmt.Remove(fmt.Length-3);
return;
}
}
}
}
No comments:
Post a Comment