XSLT / XPATH : 앞의 주석을 선택합니다
-
18-09-2019 - |
문제
XML이 다음 형식으로 구성되어 있습니다.
<blocks>
<!-- === apples === -->
<block name="block1">
...
</block>
<!-- === bananas === -->
<block name="block2">
...
</block>
<!-- === oranges === -->
<block name="block3">
...
</block>
</blocks>
내 문제는 각 블록 태그 위의 주석을 선택하는 방법을 알 수 없다는 것입니다. 다음 XSL이 있습니다.
<xsl:template match="//blocks">
<xsl:apply-templates select="block" />
</xsl:template>
<xsl:template match="block">
<xsl:apply-templates select="../comment()[following-sibling::block[@name = ./@name]]" />
<xsl:value-of select="./@name" />
</xsl:template>
<xsl:template match="comment()[following-sibling::block]">
<xsl:value-of select="."></xsl:value-of>
</xsl:template>
내가 시도하는 출력은 다음과 같습니다.
=== 사과 ===
블록 1
=== 바나나 ===
블록 2
=== 오렌지 ===
블록 3
그러나 내가 얻을 수있는 최선은 다음과 같습니다.
=== 사과 ===
=== 바나나 ===
=== 오렌지 ===
블록 1
=== 사과 ===
=== 바나나 ===
=== 오렌지 ===
블록 2
=== 사과 ===
=== 바나나 ===
=== 오렌지 ===
블록 3
그것이 차이가 있다면 PHP를 사용하고 있습니다.
해결책
두 번째 템플릿 대신 첫 번째 apply -templates에서 주석에 대해서도 템플릿을 적용 할 수 있으므로 순서대로 발생합니다. 또한이 솔루션은 소스 XML의 데이터 순서에 따라 다릅니다.
<xsl:template match="//blocks">
<xsl:apply-templates select="block | comment()" />
</xsl:template>
추신 :- 표현식에서 "//"를 최적화 할 수 있으므로 사용하지 않을 수 있습니다.
편집하다 완전한 스타일 시트
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//blocks">
<xsl:apply-templates select="block | comment()"/>
</xsl:template>
<xsl:template match="block">
<xsl:value-of select="./@name"/>
</xsl:template>
<xsl:template match="comment()">
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
블록과 주석 모두에서 값을 인쇄 한 후 NewLines를 원하는 경우 다음 진술을 추가하십시오.
<xsl:text> </xsl:text>
다른 팁
스타일 시트는 약간 지나치게 복잡합니다.
아래의 스타일 시트를 사용해 보면 원하는 출력과 일치한다는 것을 알게됩니다!
<xsl:template match="//blocks">
<xsl:apply-templates select="block" />
</xsl:template>
<xsl:template match="block">
<xsl:apply-templates select="preceding-sibling::comment()[1]" />
<xsl:value-of select="./@name" />
</xsl:template>
<xsl:template match="comment()">
<xsl:value-of select="."></xsl:value-of>
</xsl:template>
이 코드는 항상 현재 블록 태그 직전에 시작하는 1 개 또는 0 개의 주석과 일치합니다.
제휴하지 않습니다 StackOverflow