dpge74512 2011-08-31 06:25
浏览 41
已采纳

PHP中的XSLTProcessor总是删除空格

I'm trying to use XSLTProcessor to combine some XML and a XSLT stylesheet to combine to a html file. However it always results with outputting the html in 1 line.

So for example my XSLT:

<p>
    <strong>my sheet</strong>
    this is <strong>my</strong> <em>style</em>
</p>

Turns into:

<p><strong>my sheet</strong>this is <strong>my</strong><em>style</em></p>

I am using:

<xsl:preserve-space elements="*" />
<xsl:output method="html" version="4.0" encoding="iso-8859-1" indent="yes"/>

But I would like to preserve my html as it is. Anyone has any idea's?

  • 写回答

1条回答 默认 最新

  • dongli1920 2011-08-31 06:39
    关注

    preserve-space deals with the processing of elements and their contents from the data file, and does not affect how the script is parsed. The short answer is that you can't, and shouldn't.

    If you have significant whitespace (for example two spans which need a space in between to prevent the words running together) then you add it in with <xsl:text> </xsl:text>. If you don't have significant whitespace (for example, between <h1>..</h1> space <p>...), then you shouldn't try to add it in.

    XML is there to precisely, reliably transfer a document tree from one program to another, and being pretty is in no way part of its job. XSLT won't add in whitespace, because it doesn't know where it is safe to do so, and it won't take it away, because it doesn't know where that is useful. Remember XSLT know nothing about HTML; it's markup language independent. To do what you want, XSLT would need to know that it can put space around block elements (h1, p, etc) but not around spans, otherwise you might get floating punctuation:

    my cunning paragraph with
    <span>text</span>
    , and more
    

    The above is clearly not acceptable output. Because it doesn't know what elements are safe and what aren't, XSLT does the obviously correct opinion and doesn't risk malprocessing your data for sake of some pretty-printing.

    XML is not designed to be written by hand, nor read as raw data. Don't try it. Open the XML output in Firefox, and it can do the formatting for you, and if you want it took pretty, do that in another application.

    For completeness, there is in fact one safe way of doing pretty printing without affecting spacing:

    <root
      ><h1>The correct way of handling pretty-printing with XML</h1
      ><p
        >A test paragraph with a <span
        >span</span
        >, which won't break</p
      ></root
    >
    

    Finally, kill ISO-8859-1. It must die. Try to avoid h1 inside p.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部