【问题标题】:Exclude specified element from foreach从 foreach 中排除指定元素
【发布时间】:2021-08-18 22:45:46
【问题描述】:

我希望在 for-each 期间使用来自导入的 JSON 数据的结果映射排除一些元素。 我怀疑我正在运行的测试在将 XML 作为源运行时可能会起作用,但在 JSON 作为源时不起作用。

JSON 数据:

<data>
{
  "storage": {
    "pencils": 12,
    "milk": 8,
    "rulers": 4
  }
}
</data>

**

XSL:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:transform
  version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:storage="http://www.example.com/1"
  xmlns:office="http://www.example.com/2"
  xmlns:item="http://www.example.com/3"
  expand-text="yes">

  <xsl:output method="xml" indent="yes"/>

  <xsl:mode on-no-match="shallow-skip"/>

  <!-- Parse JSON to XML -->

  <xsl:template match="data">
    <storage:one>
      <xsl:apply-templates select="json-to-xml(.)"/>
    </storage:one>
  </xsl:template>

  <xsl:template match="*[@key='storage']">

    <!-- Startbase -->
    <!-- <xsl:for-each select="*"> -->

    <!-- Test[2] -->
    <xsl:for-each select="*[local-name() != 'milk']">
    <!-- Test[3] -->
      <xsl:for-each select="*[not(self::*/@key=milk)]">

      <xsl:element name="item:{@key}">
        <xsl:attribute name="office">plant-1</xsl:attribute>
        <xsl:value-of select="text()"/>
      </xsl:element>
    </xsl:for-each>
  </xsl:template>

</xsl:transform>

结果:

<?xml version="1.0" encoding="UTF-8"?>
<storage:one xmlns:item="http://www.example.com/3"
             xmlns:office="http://www.example.com/2"
             xmlns:storage="http://www.example.com/1">
   <item:pencils office="plant-1">12</item:pencils>
   <item:milk office="plant-1">8</item:milk>
   <item:rulers office="plant-1">4</item:rulers>
</storage:one>

想要的结果:

<?xml version="1.0" encoding="UTF-8"?>
<storage:one xmlns:item="http://www.example.com/3"
             xmlns:office="http://www.example.com/2"
             xmlns:storage="http://www.example.com/1">
   <item:pencils office="plant-1">12</item:pencils>
   <item:rulers office="plant-1">4</item:rulers>
</storage:one>

【问题讨论】:

    标签: json xml xslt xslt-3.0


    【解决方案1】:

    将for-each元素调整为following会排除指定元素:

    <xsl:for-each select="*[not(@key='milk')]">
    

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 2015-09-22
      • 2012-10-24
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2015-04-24
      相关资源
      最近更新 更多