【问题标题】:Wants to get value from Xml Attribute using XSLT想要使用 XSLT 从 Xml 属性中获取价值
【发布时间】:2021-10-18 17:10:53
【问题描述】:
<Document1>
    <DocumentRequest Application="Standard">
        <Doc Format="Pdf">
        <Variable Name="CUST" Value = "Aman" Type="String/>
        <Variable Name="DPID" Value = "7488493" Type="String/>
        <Variable Name="NA Number" Value = "Aman" Type="String/>
        <Variable Name="DELTA" Value = "Test" Type="String/>
        </Doc>
    </DocumentRequest>
</Document1>

这是我的 XML 我想从变量标签中获取 Name 属性的值并将其分配给不同的变量。输出应该是 -

{
"var1":"Aman",
"var2":"7488493",
"var3":"Aman",
"var4":"Test",
}

我想编写 XSLT 来做到这一点。如何编写 XSLT 并分配这些值?

【问题讨论】:

  • 请就您在尝试完成此操作时遇到的困难提出一个具体问题。否则看起来你只是在找人为你编写代码。
  • 那是什么结果格式?你说你想“分配给不同的变量”。使用哪种语言?

标签: java json xml spring-boot xslt


【解决方案1】:

只要你只有一级Variables,你就可以使用这个简单的XSLT-1.0样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:strip-space elements="*" />      
  <xsl:template match="/Document1/DocumentRequest/Doc[@Format='Pdf']">
    <xsl:text>{&#xa;</xsl:text>
      <xsl:for-each select="Variable">
        <xsl:value-of select="concat('  &quot;var',position(),'&quot;:&quot;',@Value,'&quot;')" />
        <xsl:if test="position()!=last()"><xsl:text>,&#xa;</xsl:text></xsl:if>
      </xsl:for-each>
    <xsl:text>&#xa;}</xsl:text>
  </xsl:template>        
</xsl:stylesheet>

它的输出是

{
  "var1":"Aman",
  "var2":"7488493",
  "var3":"Aman",
  "var4":"Test"
}

上面的代码匹配指定的Doc元素,然后遍历所有Variable元素。因为样式表是 XSLT 1.0 版,所以它应该可以在 Java 的 XSLT 处理器中运行,而不需要进一步复杂化。
我添加了一个xsl-if-clause 以省略最后一个元素后的逗号,使其更像 JSON。

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多