开发者

XSLTProcessor in PHP always removes white space

开发者 https://www.devze.com 2023-04-02 01:21 出处:网络
I\'m trying to use XSLTProcessor to combine some XML and a XSLT stylesheet to combine to a html file.

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><stro开发者_StackOverflow中文版ng>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?


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.

0

精彩评论

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