簡體   English   中英

如何在xml文檔中保留所有標記,結構和文本,僅替換某些XSLT?

[英]How do I preserve all tags, structure and text in an xml document replacing only some with XSLT?

我一直在嘗試將簡單的xsl樣式應用於xml文檔:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <html>
      <body>

        <xsl:for-each select="//title">
          <h1><xsl:value-of select="."/></h1>
        </xsl:for-each>

      </body>
    </html>
  </xsl:template>

</xsl:stylesheet>

不幸的是,這似乎只是簡單地忽略所有其他標簽並從輸出中刪除它們以及它們的內容,而我只留下轉換為h1s的標題。 我希望能夠做的是保留我的文檔結構,同時只替換它的一些標簽。

所以,例如,如果我有這個文件:

<section>
  <title>Hello world</title>
  <p>Hello!</p>
</section>

我可以得到這個:

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>

不太確定在XSLT手冊中的哪個地方開始尋找。

正如OR Mapper所說,解決方案是在轉換中添加一個標識模板,然后覆蓋您需要的部分。 這將是完整的解決方案:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

  <!-- Identity template -->
  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/">
    <html>
      <body>
        <xsl:apply-templates select="@* | node()" />
      </body>
    </html>
  </xsl:template>

  <xsl:template match="title">
    <h1>
      <xsl:apply-templates select="@* |node()" />
    </h1>
  </xsl:template>
</xsl:stylesheet>

在樣本輸入上運行時,會產生:

<html>
  <body>
    <section>
      <h1>Hello world</h1>
      <p>Hello!</p>
    </section>
  </body>
</html>

如果你真的只想保留原始XML但是替換<title> ,你可以刪除中間的<xsl:template> ,你應該得到結果:

<section>
  <h1>Hello world</h1>
  <p>Hello!</p>
</section>

您想要只替換<title>元素。 但是,在XSLT中,您為文檔的根元素( / )定義模板,並將整個根元素替換為模板的內容。

真正想要做的是定義一個身份轉換模板(google this,這是XSLT中的一個重要概念),基本上復制源文檔中的所有內容,以及匹配<title>元素的模板,並用新代碼替換它們, 像這樣:

<xsl:template match="title">
    <h1><xsl:value-of select="."/></h1>
</xsl:template>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM