XSLT - remove whitespace from template

前端 未结 8 1852
北恋
北恋 2020-12-02 13:23

I am using XML to store a small contact list and trying to write a XSL template that will transform it into a CSV file. The problem I am having is with whitespace in the out

8条回答
  •  自闭症患者
    2020-12-02 13:40

    In XSLT, white-space is preserved by default, since it can very well be relevant data.

    The best way to prevent unwanted white-space in the output is not to create it in the first place. Don't do:

    
      foo
    
    

    because that's "\n··foo\n", from the processor's point of view. Rather do

    
      foo
    
    

    White-space in the stylesheet is ignored as long as it occurs between XML elements only. Simply put: never use "naked" text anywhere in your XSLT code, always enclose it in an element.

    Also, using an unspecific:

    
    

    is problematic, because the default XSLT rule for text nodes says "copy them to the output". This applies to "white-space-only" nodes as well. For instance:

    
       value 
    
    

    contains three text nodes:

    1. "\n··" (right after )
    2. "·value·"
    3. "\n" (right before )

    To avoid that #1 and #3 sneak into the output (which is the most common reason for unwanted spaces), you can override the default rule for text nodes by declaring an empty template:

    
    

    All text nodes are now muted and text output must be created explicitly:

    
    

    To remove white-space from a value, you could use the normalize-space() XSLT function:

    
    

    But careful, since the function normalizes any white-space found in the string, e.g. "·value··1·" would become "value·1".

    Additionally you can use the and elements, though usually this is not necessary (and personally, I prefer explicit white-space handling as indicated above).

提交回复
热议问题