0

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>
TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
user1610952
  • 1,249
  • 1
  • 16
  • 31

3 Answers3

1

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>
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
1

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"
Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • Thanks! And then does XQuery Update change the target xml file directly? I applied the syntax above in Stylus Studio, but it doesn't seem to change anything. – user1610952 Aug 28 '12 at 12:32
  • The XQuery Update specification specifies an updating syntax, but leaves open how changes are persisted, e.g., on the file system. I think that some implementations (like MXQuery) require a flag to be set on the command line to allow overriding the XML file (to avoid accidental changes). – Ghislain Fourny Aug 28 '12 at 12:51
0

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/*
        }
}
David Lam
  • 4,689
  • 3
  • 23
  • 34