OpenXml: convert XElement to OpenXmlElement

How do I go to convert XElementto OpenXmlElement? Either my google-fu fails, or it has not been reviewed.

+5
source share
1 answer

You can convert the given OpenXmlElementto XElementusing 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 XElement to 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.

+8
source

All Articles