读取 XSLT 中的 XML 文件并使用它来构造新的 XML [英] Read XML file inside XSLT and using that to construct new XML

查看:34
本文介绍了读取 XSLT 中的 XML 文件并使用它来构造新的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取 XSLT 中的 XML 文件并检查其节点.如果它们与我应用转换的 XML 节点的值匹配,则获取 XML 节点的值并使用它来构建新的 XML 结构.

I want to read an XML file inside XSLT and check its nodes. if they match the value of XML node to which I am applying the transform, then grab the value of the XML node and use it to construct a new XML structure.

这里有一个例子来说明我的问题.我想很多人可以参考这个问题来实现类似的功能.

Here is an example to illustrate my problem. I think many people can use this question for reference to achieve similar functionality.

Referenced.xml

<xml>
  <root>
    <Id id = "1">
      <fields>
        <field>
          <name> Name1 </name>
          <value> Val1 </value>
        </field>
        <field>
          <name> Name2 </name>
          <value> Val2 </value>
        </field>
      </fields> 
    </Id>
    <Id id = "2">
    ...
    </Id>
  </root>
</xml>

Xml.xml

<XML>
  <Fields>
   <Id id = "1">
    <F1> Value1 </F1>
    <F2> Value2 </F2>
    <F1> Value3 </F1>
    <F4> Value4 </F4>
 </Id>
  </Fields>
</XML>

现在,我想创建一个转换,它将遍历 XML 文件 (Referenced.xml) 并检查两个 xml 匹配项中的 Id 位置,然后在该 ID 中,Name1= F1 然后无论它在哪里,获取该名称"的值"并创建一个像

Now, I want to create a transform which will iterate through the XML file (Referenced.xml) and check where Id inside the both xml's match and then, inside that id, Name1 = F1 and wherever it is then, fetch 'value' for that 'name' and create an XML structure like

<outputXml>
  <Field id="Val1">
    <val> Value1 </val>
  </Field>
  <Field id="Val2">
    <val> Value2 </val>
  </Field> ... and so on
</outputXml>

我知道我必须使用 document(),但我不确定如何使用您是否遍历 xsl 中的 Referenced.xml 并使用 if, else 来实现所需的功能?

I know I have to use document(), but I am not sure how do you iterate through the Referenced.xml inside xsl and use if, else to achieve the functionality needed ?

推荐答案

检查这个:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="file1" select="document('Referenced.xml')"/>
  <xsl:param name="file2" select="document('Xml.xml')"/>

  <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

  <xsl:template match="/">
    <outputXml>
      <xsl:for-each select="$file1//Id">
        <xsl:variable name="ReferencedID" select="@id"/>
        <xsl:choose>
          <xsl:when test="$ReferencedID = $file2//Id/@id">
            <xsl:for-each select="fields/field">
              <Field id="{normalize-space(value)}"><xsl:value-of select="value"/></Field>
            </xsl:for-each>
          </xsl:when>
        </xsl:choose>
      </xsl:for-each>
    </outputXml>
  </xsl:template>

</xsl:stylesheet>

获取输出:

<outputXml>
   <Field id=" Val1 "> Val1 </Field>
   <Field id=" Val2 "> Val2 </Field>
</outputXml>

这篇关于读取 XSLT 中的 XML 文件并使用它来构造新的 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆