Search code examples
xmlxpathxquerymarklogic

How to get the XML root element with its attributes, but without the content


XML:

  <Parent id='1' name='Parent_1'>
    <Children name='Children'>
      <child name='Child_2' id='2'>child2_Parent_1</child>
      <child name='Child_4' id='4'>child4_Parent_1</child>
      <child name='Child_1' id='3'>child1_Parent_1</child>
      <child name='Child_3' id='1'>child3_Parent_1</child>
    </Children>
  </Parent>

Expected Output:

 <Parent id='1' name='Parent_1'>

Hi I have given some sample XML. I have tried with X Query for getting result but I cant identify . Can you please help someone.

Thanks!


Solution

  • I would do this with a computed element constructor, the content of which only repopulates the attributes.

    let $root := (: the document, copy-pasted below :)
      <Parent id='1' name='Parent_1'>
        <Children name='Children'>
          <child name='Child_2' id='2'>child2_Parent_1</child>
          <child name='Child_4' id='4'>child4_Parent_1</child>
          <child name='Child_1' id='3'>child1_Parent_1</child>
          <child name='Child_3' id='1'>child3_Parent_1</child>
        </Children>
      </Parent>
    return element { node-name($root) } { $root/@* }
    

    Additional content can also be inserted into this element like so:

    let $root := (: the document, copy-pasted below :)
      <Parent id='1' name='Parent_1'>
        <Children name='Children'>
          <child name='Child_2' id='2'>child2_Parent_1</child>
          <child name='Child_4' id='4'>child4_Parent_1</child>
          <child name='Child_1' id='3'>child1_Parent_1</child>
          <child name='Child_3' id='1'>child3_Parent_1</child>
        </Children>
      </Parent>
    return element { node-name($root) } {
      $root/@*,
      <foo/>,
      <bar/>
    }