0

I am creating a XElement via htmlconverter Class from OpenXML Powertools.

XElement html = HtmlConverter.ConvertToHtml(doc, settings)

Now I'm trying to add some new nodes like

html.Element("head").Add(new XElement("link",
                    new XAttribute("href", "stylesheet.css"),
                    new XAttribute("rel", "stylesheet"),
                    new XAttribute("type", "text/css")));

But html.Element("head") is always returning null and i get a NullReferenceException Error from Visual Studio while running in Debug Mode and i still have no idea why.

This is the code based on this article, which i am currently using in my project. I think it has to do something with the htmlconverter because it works if i create a handmade XElement.

// This example shows the simplest conversion. No images are converted.
// A cascading style sheet is not used.
byte[] byteArray = File.ReadAllBytes("Test.docx");
using (MemoryStream memoryStream = new MemoryStream())
{
    memoryStream.Write(byteArray, 0, byteArray.Length);
    using (WordprocessingDocument doc =
        WordprocessingDocument.Open(memoryStream, true))
    {
        HtmlConverterSettings settings = new HtmlConverterSettings()
        {
            PageTitle = "My Page Title"
        };
        XElement html = HtmlConverter.ConvertToHtml(doc, settings);

        // Note: the XHTML returned by ConvertToHtmlTransform contains objects of type
        // XEntity. PtOpenXmlUtil.cs defines the XEntity class. See
        // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx
        // for detailed explanation.
        //
        // If you further transform the XML tree returned by ConvertToHtmlTransform, you
        // must do it correctly, or entities do not serialize properly.

        File.WriteAllText("Test.html", html.ToStringNewLineOnAttributes());
    }
}
user3120053
  • 21
  • 1
  • 2
  • html.Firstnode works, so i'm able to create my own head XElement and replace it with the firstnode in html (which always should be head). It works for me at the moment, but i'm still not satisfied with this solution. – user3120053 Dec 24 '13 at 09:37

1 Answers1

0

You missed the namespace, try this instead:

XNamespace w = "http://www.w3.org/1999/xhtml";
var head = html.Element(w + "head");
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44