Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenXml: Convert an XElement to an OpenXmlElement

How would I go about converting an XElement to an OpenXmlElement? Either my google-fu fails or this has not been addressed.

like image 956
emd Avatar asked Dec 07 '11 16:12

emd


People also ask

What is DocumentFormat OpenXml?

The Open XML SDK provides tools for working with Office Word, Excel, and PowerPoint documents. It supports scenarios such as: - High-performance generation of word-processing documents, spreadsheets, and presentations. - Populating content in Word files from an XML data source.

How do I add DocumentFormat OpenXml reference?

Go to your Solution Explorer > right click on references and then click Manage NuGet Packages . Then search in tab "Online" for DocumentFormat. OpenXml and install it.

Is Open XML open source?

Today MS Open Tech has announced the release of the Open XML SDK version 2.5 as open source software (Apache 2.0 license) under the stewardship of the . NET Foundation.


1 Answers

You can convert a given OpenXmlElement to a XElement using the following code:

OpenXmlElement el = ...; // Code to get the xml element from your office doc.

// Then use XElement.Parse and the OuterXml property.
XElement xel = XElement.Parse(el.OuterXml);

To convert an XElement to an OpenXmlElement try the following code:

XElement xe = ...;
using(StreamWriter sw = new StreamWriter(new MemoryStream()))
{
  sw.Write(xe.ToString());
  sw.Flush();
  sw.BaseStream.Seek(0, SeekOrigin.Begin);

  OpenXmlReader re = OpenXmlReader.Create(sw.BaseStream);

  re.Read();
  OpenXmlElement oxe = re.LoadCurrentElement();
  re.Close();
}

Hope, this helps.

like image 157
Hans Avatar answered Oct 12 '22 22:10

Hans