XQuery结合了两个xml文件

问题描述 投票:1回答:1

目前有两个XML文件,并希望将它们组合起来创建1个XML文件。

XML 1(recipes.xml):

<recipes>
    <recipe id="182">
        <name>Hamburger</name>
        <description>Hamburgers are created...</description>
        <chapter>1</chapter>
        <page_number>13</page_number>
    </recipe>
    <recipe id="185">
        <name>Muffins</name>
        <description>Muffins picked with...</description>
        <chapter>2</chapter>
        <page_number>43</page_number>
    </recipe>
<recipes>

XML 2(ingredients.xml):

<ingredients>
    <ingredient id="5">
        <name>Burger Buns</name>
        <recipe_id>182</recipe_id>
        <price>$3.00</price>
        <quantity>13</quantity>
    </ingredient>
    <ingredient id ="111">
        <name>Carrot</name>
        <recipe_id>182</recipe_id>
        <price>2.50</price>
        <quantity>1</quantity>
    </ingredient>
    <ingredient id ="535">
        <name>Blueberry</name>
        <recipe_id>185</recipe_id>
        <price>$5.00</price>
        <quantity>1 Packet of 200 grams</quantity>
    </ingredient>
<ingredients>

而且我希望它们结合起来,配方有这样的成分:输出:

<food>
    <recipe id ="182">
        <name>Hamburger</name>
        <description>Hamburgers are created...</description>
        <chapter>1</chapter>
        <page_number>13</page_number>
            <ingredient id ="5">
                <name>Burger Buns</name>
                <price>$3.00</price>
                <quantity>13</quantity>
            </ingredient>
            <ingredient id ="111">
                <name>Carrot</name>
                <price>$2.50</price>
                <quantity>1</quantity>
            </ingredient>
    </recipe>
    <recipe id ="185">
        <name>Muffins</name>
        <description>Muffins picked with...</description>
        <chapter>2</chapter>
        <page_number>43</page_number>
            <ingredient id ="535">
                <name>Blueberry</name>
                <price>$5.00</price>
                <quantity>1 Packet of 200 grams</quantity>
            </ingredient>
    </recipe>
</food>

目前正在尝试在名为BaseX的程序中进行合并。我可以使用单个for循环执行简单查询,但是将2个单独的文档放在一起会遇到麻烦。

xquery
1个回答
1
投票

您可以从其他文档中选择与id匹配的元素,然后将其填入:

<food>
{
    for $recipe in recipes/recipe
    let $ingredients := $doc2/ingredients/ingredient[$recipe/@id = recipe_id]
    return
        <recipe>
            {
                $recipe/(@*, *),
                $ingredients/<ingredient>{@*, * except recipe_id }</ingredient>
            }
        </recipe>
}
</food>

您可以作为外部变量读取的另一个文档或使用doc('ingredients.xml'),带有外部变量的完整示例(默认为示例的紧凑性为内联XML)位于https://xqueryfiddle.liberty-development.net/6qM2e2j

© www.soinside.com 2019 - 2024. All rights reserved.