使用Converter后修改XElement的问题

时间:2013-12-23 17:27:03

标签: c# xhtml openxml xelement

我正在通过OpenXML Powertools的htmlconverter类创建一个XElement。

XElement html = HtmlConverter.ConvertToHtml(doc, settings)

现在我正在尝试添加一些新节点,如

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

但是html.Element(“head”)总是返回null,并且在调试模式下运行时我从Visual Studio得到NullReferenceException错误,我仍然不知道为什么。

这是基于此article的代码,我目前正在我的项目中使用它。我认为它必须对htmlconverter做一些事情,因为如果我创建一个手工制作的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());
    }
}

1 个答案:

答案 0 :(得分:0)

你错过了命名空间,试试这个:

XNamespace w = "http://www.w3.org/1999/xhtml";
var head = html.Element(w + "head");