Extracting CML from a Chem4Word authored document (C#)

My previous post was the first in a series demonstrating how CML embedded in DOCX files could be extracted (in that case using Java). For completeness I thought I ought to post some code to accomplish the same thing in C#. This should also allow people to get used to the packaging tools before we build up functionality in later posts.

If you would like a file containing CML to test this out with, one is available here.

Now for the code:


using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace Chem4Word.Tools 
{
  public class OOXMLTools 
  {
    public ICollection GetCML(string path) 
    {
      ICollection list = new List();
      using (Package package = Package.Open(path, FileMode.Open)) 
      {
        foreach (PackagePart packagePart in package.GetParts()) 
        {
          if (packagePart.ContentType == "application/xml") 
          {
            using (StreamReader streamReader = 
               new StreamReader(packagePart.GetStream())) 
            {
              try 
              {
                XDocument xDocument = 
                  XDocument.Parse(streamReader.ReadToEnd());
                if (xDocument.XPathSelectElements(
              "//*[local-name()='cml' and namespace-uri()=
              'http://www.xml-cml.org/schema']").Count() > 0) 
                {
                  list.Add(xDocument);
                }
              }
              catch 
              {
                  // not valid XML so therefore can't be CML
              }
            }
          }
        }
      }
      return list;
    }
  }
}

So there we go. Pretty similar to the Java version really. Just in case you were wondering, I know I haven’t done a load of exception checking.

Advertisements

One Response to Extracting CML from a Chem4Word authored document (C#)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: