How to prevent self closing tags as well empty tags after transforming

余生长醉 提交于 2021-01-27 13:39:24

问题


I have in an input file:

<a></a>
<b/>
<c>text</c>

I need to converting this to string. Using transformer I am getting below output:

<a/> <!-- Empty tags should not collapse-->
<b/>
<c>text</c>

If I use xslt and output method is "HTML", I get the below output:

<a></a> <!-- This is as expected-->
<b></b> <!-- This is not expected-->
<c>text</c>

I want the structure same as in input file. It is required in my application since I need to calculate index and it will be very difficult to change the index calution logic.

What would be the correct XSLT to use?


回答1:


What XSLT processor? XSLT is merely a language to transform xml so "html output" is dependent on the processor.

I'm going to guess this first solution is too simple for you but i've had to use this to avoid processing raw html

<xsl:copy-of select="child::node()" /> 

as this should clone the raw input. In my case, I have used the following to extract all nodes that had the raw attribute:

<xsl:for-each select="xmlData//node()[@raw]">
            <xsl:copy-of select="child::node()" />
</xsl:for-each>

Other options:

2) Add an attribute to each empty node depending on what you want it to do later ie role="long", role="short-hand".

3) Loop through each node (xsl:for-each)

<xsl:choose>
<xsl:when test="string-length(.)=0"> <!-- There is no child-->
<xsl:copy-of select="node()" />
</xsl:when>
<xsl:otherwise>
...whatever normal processing you have
</xsl:otherwise>

4) Redefine your problem. Both are valid XHTML/XML, so perhaps your problem can be reframed or fixed elsewhere.

Either way, you may want to add more information in your question so that we can reproduce your problem and test it locally.

P.S. Too much text/code to put in a comment, but that's where this would belong.




回答2:


A possible alternative is to use disable-output-escaping like this:

<xsl:text disable-output-escaping="yes">&lt;a&gt;&lt;/a&gt;</xsl:text>

But I understand that this is a dirty solution...



来源:https://stackoverflow.com/questions/13956964/how-to-prevent-self-closing-tags-as-well-empty-tags-after-transforming

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!