1
votes

I am using BaseX to store XML data with multiple item nodes in the following format:

<root>
  <item id="Root" parent_id="0" type="folder">
    <content>
      <name>Root</name>
    </content>
  </item>

  <item id="One" parent_id="Root" type="file">
    <content>
      <name>First File in the Tree</name>
    </content>
  </item>

  <item id="Two" parent_id="Root" type="file">
    <content>
      <name>Second File in the Tree</name>
    </content>
  </item>
</root>

I am trying to update the parent_id on one of the 'item' nodes to another item node's id attribute.

The tree before running the XQuery expression:

Root
∟ First File in the Tree
∟ Second File in the Tree

I am trying to figure out the correct XQuery expression to change the parent of one of the items from root to "one" item, so that my tree now looks like this:

Expected result tree:

Root
∟ First File in the Tree
    ∟ Second File in the Tree

Since the attribute parent_id controls this, I am looking to update exactly that.

1

1 Answers

2
votes

If all you want to do is to update the @parent_id attribute, use a simple updating query like

  replace value of node //item[@id='Two']/@parent_id with 'One'

But: this wouldn't actually change the XML tree, but only the one you're representing in XML (although I believe that this is what your question was about). A more XML-like approach to store the tree would be directly mapping the tree you want to have to XML:

<root>
  <item id="Root" type="folder">
    <content>
      <name>Root</name>
    </content>
    <item id="One" type="file">
      <content>
        <name>First File in the Tree</name>
      </content>
      <item id="Two" type="file">
        <content>
          <name>Second File in the Tree</name>
        </content>
      </item>
    </item>
  </item>
</root>

Or even more concise, holding the same information:

<folder id="Root" name="Root">
  <file id="One" name="First File in the Tree">
    <file id="Two" name="Second File in the Tree" />
  </file>
</folder>