Объединить два или более XML-файлов, используя xslt-3

У меня много XML-файлов, которые мне нужно объединить в один: hotel1.xml

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

<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>

<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>

</breakfast_menu>
</menu>

Отель2:

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

<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>

</breakfast_menu>
</menu>

hotel3.xml:

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

<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>

<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>

</breakfast_menu>
</menu>

Мне нужно сначала добавить значение к элементу name, чтобы узнать, из какого он файла, и объединить все xml-файлы.

Желаемый результат:

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

<food>
<name>Belgian Waffles-hotel1</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>

<food>
<name>Strawberry Belgian Waffles-hotel1</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>

<food>
<name>Berry-Berry Belgian Waffles-hotel2</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>

<food>
<name>French Toast-hotel3</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>

<food>
<name>Homestyle Breakfast-hotel3</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>

</breakfast_menu>
</menu>

в данной папке мне нужно объединить все XML-файлы в один. Просто объедините их содержимое. Нет проверок или обновлений. Кроме того, мне нужно сохранить в элементе имени, каждый файл пришел, для дальнейшего использования

Вот мое испытание. Мне нужна кто-то более опытная помощь, чтобы использовать последнюю версию xslt-3 и как XML-файлы, которые существуют в данной папке.

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

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

  <xsl:template match="breakfast_menu">
    <xsl:copy>
      <xsl:apply-templates select="*"/>
      <xsl:apply-templates select="document('hotel1.xml')/menu/breakfast_menu/*" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

1 ответ

Решение

В XSLT есть разные способы сделать это, один из них - попробовать новый xsl:merge инструкция, но, как я столкнулся с проблемой, используя это с Saxon 9.8 (см. https://saxonica.plan.io/issues/3883 и https://saxonica.plan.io/issues/3884) здесь по-другому, это кажется, вы просто хотите скопировать все элементы с определенного уровня, в вашем случае food элементы с третьего уровня; универсальная таблица стилей, чтобы сделать то, что принимает выражение выбора в качестве статического параметра (я сохранил его как */*/* но вы можете, конечно, изложить это для ваших документов как menu/breakfast_menu/food), URI и шаблон имени файла для входных файлов, а затем запускается с xsl:initial-template (опция командной строки -it для саксонской командной строки) выглядит следующим образом:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all"
    expand-text="yes"
    version="3.0">

    <xsl:param name="input-uri" as="xs:string" select="'.'"/>

    <xsl:param name="file-pattern" as="xs:string" select="'hotel*.xml'"/>

    <xsl:param name="merge-select-expression" as="xs:string" static="yes" select="'*/*/*'"/>

    <xsl:param name="xslt-pattern-to-add-file-name" as="xs:string" static="yes" select="$merge-select-expression || '/name'"/>

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:mode on-no-match="shallow-copy" streamable="yes"/>

    <xsl:template _match="{$xslt-pattern-to-add-file-name}">
        <xsl:comment>Copied this {node-name()} element from {tokenize(document-uri(/), '/')[last()]}</xsl:comment>
        <xsl:next-match/>
    </xsl:template>

    <xsl:template name="xsl:initial-template">
        <xsl:sequence select="mf:append-docs(uri-collection($input-uri || '?select=' || $file-pattern))"/>
    </xsl:template>

    <xsl:function name="mf:append-docs" as="document-node()">
        <xsl:param name="doc-uris" as="xs:anyURI+"/>
        <xsl:source-document href="{head($doc-uris)}" streamable="yes">
            <xsl:apply-templates select="." mode="construct">
                <xsl:with-param name="remaining-doc-uris" as="xs:anyURI*" select="tail($doc-uris)" tunnel="yes"/>
            </xsl:apply-templates>
        </xsl:source-document>
    </xsl:function>

    <xsl:mode name="construct" on-no-match="shallow-copy" streamable="yes"/>

    <xsl:template _match="{string-join(tokenize($merge-select-expression, '/')[position() lt last()], '/')}" mode="construct">
        <xsl:param name="remaining-doc-uris" as="xs:anyURI*" tunnel="yes"/>
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates/>
            <xsl:for-each select="$remaining-doc-uris">
                <xsl:source-document href="{.}" streamable="yes">
                    <xsl:apply-templates _select="{$merge-select-expression}"/>
                </xsl:source-document>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Он должен работать довольно просто, просто настраивая параметры и, возможно, настраивая тело <xsl:template _match="{$xslt-pattern-to-add-file-name}"> В качестве шаблона я выбрал выводить имя файла в комментарии, а не выбрасывать его в содержимое элемента.

Для ваших трех образцов в подкаталоге hotel-stackru-test где таблица стилей append.xsl есть и саксонская командная строка -it -xsl:.\append.xsl input-uri=hotel-stackru-test file-pattern=hotel*.xml Я получаю вывод

<menu>
   <breakfast_menu>
      <food><!--Copied this name element from hotel1.xml-->
         <name>Belgian Waffles</name>
         <price>$5.95</price>
         <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
         <calories>650</calories>
      </food>
      <food><!--Copied this name element from hotel1.xml-->
         <name>Strawberry Belgian Waffles</name>
         <price>$7.95</price>
         <description>Light Belgian waffles covered with strawberries and whipped cream</description>
         <calories>900</calories>
      </food>
      <food><!--Copied this name element from hotel2.xml-->
         <name>Berry-Berry Belgian Waffles</name>
         <price>$8.95</price>
         <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
         <calories>900</calories>
      </food>
      <food><!--Copied this name element from hotel3.xml-->
         <name>French Toast</name>
         <price>$4.50</price>
         <description>Thick slices made from our homemade sourdough bread</description>
         <calories>600</calories>
      </food>
      <food><!--Copied this name element from hotel3.xml-->
         <name>Homestyle Breakfast</name>
         <price>$6.95</price>
         <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
         <calories>950</calories>
      </food>
   </breakfast_menu>
</menu>

Код должен использовать потоковую передачу с Saxon 9.8 EE и обычную обработку XSLT с Saxon 9.8 HE или PE.

Другие вопросы по тегам