How to get the root XML element with its attributes but no 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 Result:

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

      

Hi I have given some XML sample. I tried with X Query to get the result, but I cannot determine. Could you please help someone.

Thank!

+3


source to share


1 answer


I would do this with a computed element constructor whose content 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 as follows:

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/>
}

      

+3


source







All Articles