开发者

MSXML XHTML and embedded CSS

I have an Excel workbook that is used as a starting point to generate a user-fillable form in our internal system. As an aide to the users creating these workbook, I'm trying to add a preview function, that takes that spreadsheet, does some VBA magic to generate an HTML file, and then display that in their browser.

I have the basic structure done, using MSXML to write out XHTML, so far, so good. Now, I'm hitting an issue with embedding the style开发者_StackOverflow sheet.

The style sheet is contained in a string in the VBA code, and I'm trying to add it into a <style> tag in the header, which is straightforward. Where I'm having the issue is I'm using CSS selectors in the stylesheet, with > causing me issues, since MSXML wants to encode that as a XML escape sequence, breaking the CSS. I've tried adding the stylesheet within a CDATA block, but then the browser just ignores it.

tl;dr: How can I embed a stylesheet containing > into an HTML file generated with MSXML?

EDIT: Here's a block of code that reproduces this behavior. Put it into a Sub in Excel or a VBA-using program of your choice, run it, and view the source:

Dim doc As DOMDocument
Dim htmlRoot As IXMLDOMElement
Dim bodyRoot As IXMLDOMElement
Dim headRoot As IXMLDOMElement
Dim style As IXMLDOMElement

Set doc = New DOMDocument
Set htmlRoot = doc.createElement("html")
Set bodyRoot = doc.createElement("body")
Set headRoot = doc.createElement("head")

Set style = doc.createElement("style")
style.appendChild doc.createTextNode(".section>.title{font-weight: bold;}")
style.setAttribute "type", "text/css"

headRoot.appendChild style

htmlRoot.appendChild headRoot
htmlRoot.appendChild bodyRoot

doc.appendChild htmlRoot

Dim fs As FileSystemObject
Dim sh
Dim tempFolder As String
Set fs = New FileSystemObject
Set sh = CreateObject("WScript.Shell")
tempFolder = fs.GetSpecialFolder(TemporaryFolder)

Dim fileName As String
fileName = tempFolder + "\preview.html"
doc.Save fileName
sh.Run fileName


Perhaps instead of trying to store CSS characters which will be interpreted as XML markup, you could produce the XHTML using your existing method, but instead of inserting the CSS using MSXML, insert a placeholder, and replace it after you have finished building the XHTML. Something like this:

style.appendChild doc.createTextNode("{css}")

' some more XHTML building here.

Dim html As String
Dim css As String

css = ".section>.title{font-weight: bold;}"
html = Replace(doc.Text, "{css}", css)

' Save the html here...

This way, you can embed whatever you want in the XHTL, without having to worry about MSXML trying to escape it for you.


The XML escape sequence for > is &gt; (meaning GreaterThan)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜