0
votes

I'd like to change the attribute of certain elements in an xml document. What's the simplest way? (Xquery is the best, or I can handle python somehow)

Change /root/person[1]/@name to "Jim"
change /root/person[2]/@name to "John"

Sample.xml

<root>
    <person name="brian">
    <number>1</number>
    <school>Y</school>
    <age>18</age>
    </person>
    <person name="brian">
    <number>1</number>
    <school>Y</school>
    <age>18</age>
    </person>
</root>

Sampe_result.xml

<root>
    <person name="Jim">
    <number>1</number>
    <school>Y</school>
    <age>18</age>
    </person>
    <person name="John">
    <number>1</number>
    <school>Y</school>
    <age>18</age>
    </person>
</root>
3

3 Answers

1
votes

Making small changes to XML documents is most easily achieved in XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- By default, copy elements and attributes unchanged -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*"/>
    </xsl:copy>
  </xsl:template>

  <!-- Change /root/person[1]/@name to "Jim" -->
  <xsl:template match="/root/person[1]/@name">
    <xsl:attribute name="name">Jim</xsl:attribute>
  </xsl:template>

  <!-- Change /root/person[2]/@name to "John" -->
  <xsl:template match="/root/person[2]/@name">
    <xsl:attribute name="name">John</xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
1
votes

Try XQuery Update if your implementation supports it.

replace value of node /root/person[1]/@name with "Jim",
replace value of node /root/person[2]/@name with "John"
0
votes

hmm maybe just reconstruct it and make changes in a FLOWR? -->

element root {
    for $person at $i in doc('Sample.xml')/root/person
    let $new-name := if($i eq 1) then "Jim" else "John"
    return 
        element person {
            attribute name { $new-name },
            $person/*
        }
}