Попытка преобразовать xsl-файл и xml-файл в html, а затем отобразить его в объекте WebBrowser - PullRequest
0 голосов
/ 12 апреля 2011

Итак, я пытаюсь преобразовать xml-файл, который использует xsl-файл, а затем преобразовать оба из них в html, который я могу связать с объектом WebBrowser. Вот что у меня до сих пор не работает:

        protected string ConvertXSLAndXMLToHTML(string xmlSource, string xslSource)
        {

        string resultDoc = Application.StartupPath + @"\result.html";
        string htmlToPost;


        try
        {
            XPathDocument myXPathDoc = new XPathDocument(xmlSource);
            XslTransform myXslTrans = new XslTransform();

            //load the Xsl 
            myXslTrans.Load(xslSource);

            //create the output stream
            XmlTextWriter myWriter = new XmlTextWriter(resultDoc, null);

            //do the actual transform of Xml
            myXslTrans.Transform(myXPathDoc, null, myWriter);

            myWriter.Close();

            StreamReader stream = new StreamReader(resultDoc);
            htmlToPost = stream.ReadToEnd();
            stream.Close();

            File.Delete(resultDoc);

            return (htmlToPost);


         }

         catch (FileNotFoundException fileEx)
         {
            MessageBox.Show("File Not Found: " + fileEx.FileName, "File Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return null;
        }


        catch (Exception ex)
        {
            MessageBox.Show("General Exception: " + ex.Message, "Exception Thrown" , MessageBoxButtons.OK, MessageBoxIcon.Error);
            return null;
        }

    }

Этот код находится в функции, которая возвращает htmlToPost, а возвращаемые данные привязываются к веб-браузеру следующим образом:

            // webReport is the WebBrowser object
            // htmlString is the html passed to the function
            // that will bind the html text to the WebBrowser object

            webReport.Navigate("about:blank");
            IHTMLDocument2 test = (IHTMLDocument2)webReport.Document.DomDocument;
            test.write(htmlString);
            webReport.Document.Write(string.Empty);
            webReport.DocumentText = htmlString;

Я знаю, что XslTransform устарел, но все примеры в сети используют его, поэтому я использую его.

Я получаю следующую ошибку:

Произошла ошибка во время выполнения. Вы хотите отладить?

Линия: 177 Ошибка: ожидается ')'

Это происходит, когда этот код пытается выполнить:

        IHTMLDocument2 test = (IHTMLDocument2)webReport.Document.DomDocument;
        test.write(htmlString);  //this is the actual line that causes the error and it traces into assembly code.

Заранее благодарим за любую помощь, которую вы можете оказать мне.

РЕДАКТИРОВАТЬ # 1: Если я нажму "Нет" для отладки ошибок, страница отобразится так, как мне бы хотелось.

1 Ответ

0 голосов
/ 12 апреля 2011

Я делаю это в своем проекте

Создайте временный файл:

string ReportTempPath = Path.Combine(Path.GetTempPath(), "pubreport" + Guid.NewGuid().ToString() + ".html");

Сохраните содержимое:

var root =
                new XElement(ns + "html",
                    new XElement(ns + "head",
                        new XElement(ns + "title", "Publisher Report"),

// ...

var docType = new XDocumentType("html",
              "-//W3C//DTD XHTML 1.0 Strict//EN",
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null);

    var doc =
        new XDocument(
            new XDeclaration("1.0", "utf-8", "no"),
            docType,
            root
        );

    doc.Save(path);

Затем передайте MemoryStream в элемент управления веб-браузера.

webBrowser1.DocumentStream = new MemoryStream(File.ReadAllBytes(ReportTempPath));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...