user1610952
user1610952

Reputation: 1289

editing xml using xquery or something

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>

Upvotes: 0

Views: 1973

Answers (3)

Jens Erat
Jens Erat

Reputation: 38682

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"

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163322

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>

Upvotes: 1

David Lam
David Lam

Reputation: 4948

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

Upvotes: 0

Related Questions