首页 > 解决方案 > 使用其他来源的数据填充 XML 的免费解决方案

问题描述

我必须基于多个数据源(数据库、休息服务)生成 XML 文档。例如来自多个公司系统的人员列表person.xml

<persons>
  <person>
    <name></name>
    <birthdate></birthdate>
     ...
  </person>
   ...
</persons>

我不想编写太多代码(请不要用任何编程语言编写循环、条件和流)或为此使用商业产品。我同意将所有外部数据收集到另一个 XML 中,例如: data.xml

<data>
  <source name="database"> 
    <persons>...</persons>   
  </source>
  <source name="restservice1">
    <persons>...</persons>   
  </source>
  <source name="restservice2">
    <persons>...</persons>   
  </source>
</data>

我想要一个模板文件来描述如何基于数据文件 (data.xml) 形成 XML 文档 (persons.xml) - 哪种技术/产品最灵活?

我已经读到 XSLT 今天已经过时了,过去我对 XSLT 感到非常痛苦,以至于我想把我的手放在 XSLT 以外的任何东西上。

如何呈现来自杂项来源的数据的任何其他方法也是可以接受的

标签: xml

解决方案


XSLT 并没有过时,事实上它有一个非常活跃的社区。

避免循环将限制达到您的目标。即使不直接添加循环的编程语法,它们也经常在后台被调用。

我同意 XSLT 作为编程语言来自其他语言有点陡峭。最好的方法是将源文件视为数据库(即使不是),但在构建模板查询时会有所帮助。

学习 XSLT 是值得的。如果您有耐心,您将获得速度。选择更简单的语言或工具很可能会在以后的模板之旅中给您带来问题。

下面是 XSLT 3.0 的一部分,可以满足您的需求,但它可能与您要求的不完全一样,因为您遗漏了一些信息,例如应该在 XML 中呈现的内容以及数据应该如何分组。因为没有运行循环代码实际上是硬编码的,并且在您需要扩展 XML 源数据文件时不会有太多用处。

数据.xml

<persons
  xmlns:persons="http://www.example.com/1"
  >
  <person>
    <name>Frank</name>
    <birthdate>21st of May 2021</birthdate>
  </person>
  <person>
    <name>Anita</name>
    <birthdate>5st of May 2021</birthdate>
  </person>
</persons>

xsl

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

<xsl:transform version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.example.com/0"
  xmlns:persons="http://www.example.com/1"
  xmlns:males="http://www.example.com/2"
  xmlns:females="http://www.example.com/3"
>

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

  <xsl:template match="/">

    <data>

      <source name="database">

        <males:persons>
          <xsl:value-of select="persons/person[1]"/>
        </males:persons>
        <females:persons>
          <xsl:value-of select="persons/person[2]"/>
        </females:persons>

      </source>

    </data>

  </xsl:template>

</xsl:transform>

结果

<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="http://www.example.com/0"
      xmlns:females="http://www.example.com/3"
      xmlns:males="http://www.example.com/2"
      xmlns:persons="http://www.example.com/1">
   <source name="database">
      <males:persons>
    Frank
    21st of May 2021
  </males:persons>
      <females:persons>
    Anita
    5st of May 2021
  </females:persons>
   </source>
</data>

推荐阅读