emd
emd

Reputation: 1223

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.

Upvotes: 5

Views: 5556

Answers (1)

Hans
Hans

Reputation: 13040

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.

Upvotes: 10

Related Questions