Могу ли я добавить теги <p> </p> вокруг текстового содержимого в элементах XML с помощью XSLT 1.0?

Джоэл

В настоящее время я собираю динамический HTML-шаблон, которому способствует простая комбинация документов из XML-данных и XSLT (1.0), но недавно я столкнулся с проблемой, по которой я был бы признателен за совет.

Установив соединение между моими документами XML и XSLT, я использовал стандартную <xsl:value-of select="xxxxxx/xxxxxx"/>команду для извлечения текстовых узлов, содержащихся в моих элементах XML, и вывода их в шаблон HTML. Большой!

Однако я столкнулся с проблемой в этом процессе.

Один из моих XML-элементов (в этом примере <synopsis></synopsis>) содержит большой объем текста, в настоящее время разделенный разрывами строк, который в идеале мне нужно отобразить в (трех отдельных) абзацах на моей HTML-странице.

Позвольте мне поделиться с вами примером XML-данных :

<bookstore>
  <book>
    <title>Harry Potter and the Philosopher's Stone</title>
    <author>J K. Rowling</author>
    <year>1997</year>
    <price>3.99</price>
    <publisher>Bloomsbury (UK)</publisher>
    <synopsis>
         Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel. 

         The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry. 

         With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.
   </synopsis>
 </book>
 <book>
    <title>The Girl with the Dragon Tattoo</title>
    <author>Stieg Larsson</author>
    <year>2005</year>
    <price>5.99</price>
    <publisher>Norstedts Förlag (SWE)</publisher>
    <synopsis>
         In Stockholm, Sweden, journalist Mikael Blomkvist, co-owner of Millennium magazine, has lost a libel case brought against him by businessman Hans-Erik Wennerström. Lisbeth Salander, a brilliant but troubled investigator and hacker, compiles an extensive background check on Blomkvist for business magnate Henrik Vanger, who has a special task for him. 

         In exchange for the promise of damning information about Wennerström, Blomkvist agrees to investigate the disappearance and assumed murder of Henrik's grandniece, Harriet, 40 years ago. 

         After moving to the Vanger family's compound, Blomkvist uncovers a notebook containing a list of names and numbers that no one has been able to decipher.
    </synopsis>
  </book>
</bookstore>

При использовании этой <xsl:value-of select="xxxxxx/xxxxxx"/>команды мой текущий вывод для <synopsis></synopsis>элементов, очевидно, представляет собой непрерывный блок текста без пробелов (между тремя абзацами); Пример Гарри Поттера :

    Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel.The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry.With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.

Чего я хотел бы достичь в моем выводе HTML (надеюсь, с помощью шаблона в XLST 1.0), так это:

    <p>Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel.</p>

    <p>The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry.</p>

    <p>With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.</p>

Итак, вот мой главный вопрос. Можно ли решить (см. Выше) с помощью некоторой формы шаблона в моем файле XSLT (1.0)? Это вообще возможно?

Могу ли я потенциально установить строковую переменную (of <synopsis>), а затем выполнить поиск по ней и найти каждую полную остановку / разрыв строки в текстовом отрывке и в этих точках обернуть <p></p>тегами эту часть выделения строки, чтобы сформировать мои абзацы?

Если это действительно перспектива, я бы хотел развить ее в будущем и, возможно, добавить некоторые дополнительные HTML-теги, такие как <ol><li><li></ol>и т. Д.

Любая помощь или совет о том, достижимо ли это, будут тепло приняты.

michael.hor257k

Я не думаю, что необходимо изменять исходный ввод XML. Вы можете просто использовать символ перевода строки в качестве разделителя (и применить некоторую нормализацию к оставшимся пробелам):

<xsl:template match="synopsis">
    Synopsis: <span style="color:#38A930">
    <xsl:call-template name="tokenize">
        <xsl:with-param name="text" select="."/>
    </xsl:call-template>
    </span>
    <br/>
</xsl:template>

<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'&#10;'"/>
        <xsl:variable name="token" select="normalize-space(substring-before(concat($text, $delimiter), $delimiter))" />
        <xsl:if test="$token">
            <p>
                <xsl:value-of select="$token"/>
            </p>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관