0

我需要将多个节点内的新元素插入到输入 XML 文档中。然后,我需要更新和检索更新后的 XML 文档。

我正在使用Anypoint Studio,由于 xquery Transformation 模块支持 XQuery 3.0,我想我可以使用insert-before函数,并且由于元素必须插入多个节点,我需要使用for循环来循环多个匹配项。

我是 xQuery 的新手,所以对于任何初学者类型的错误,我提前道歉。

这是我需要转换的 XML 文档的示例:

<Catalog>
  <Item>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
</Catalog>

我需要在每个Item节点的位置 1 中插入标签名称。像这样的东西:

<Catalog>
  <Item>
    <Name>SomeName1</Name>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <Name>SomeName2</Name>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <Name>SomeName3</Name>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
</Catalog>

由于我对 XQuery 的了解不足,我尝试了许多查询,但每次都遇到语法错误。例如,我尝试了这个查询:

xquery version "3.0";
declare copy-namespaces no-preserve, inherit;
declare variable $document external;

declare variable $items := $document/Catalog/Item;

for $item in $items
return
   <Item>
     <Name>{ }</Name>
     { $item/Property1 } 
     { $item/Property2 }
     { $item/Property3 }
   </Item>

...但生成的 XML 文档(使用 anypoint Studio 中的 xquery 转换模块的字符串数组)不包含根节点。

任何帮助将不胜感激。

4

2 回答 2

1

我没有 Mulesoft 及其 Anypoint Studio。

我正在使用 BaseX v.9.5.1

XQuery

declare context item := document {
<Catalog>
  <Item>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
</Catalog>
};

<Catalog>
{
  let $new := <newElement>somevalue</newElement>
  for $x in ./Catalog/Item
  return <Item>
    {$new, $x/*}
  </Item>
  
}
</Catalog>

输出

<Catalog>
  <Item>
    <newElement>somevalue</newElement>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
  <Item>
    <newElement>somevalue</newElement>
    <Property1>Prop1</Property1>
    <Property2>Prop2</Property2>
    <Property3>Prop3</Property3>
  </Item>
</Catalog>
于 2021-04-12T14:27:13.450 回答
1

你不需要insert-before

/*!element { node-name() } {
    Item ! element { node-name() } {
        insert-before(*, 1, <Name/>)
    }
}

将是使用它的一种方式,虽然

/*!element { node-name() } {
    Item ! element { node-name() } {
        <Name/>, *
    }
}

做这项工作。

请注意,如果您的处理器支持 XQuery 更新(例如 BaseX),它可能会更合适。

于 2021-04-12T14:58:26.773 回答