Piyush
Piyush

Reputation: 5315

how can i parse the xml file in tcl script and read the some tag attribute and change the that attribute value

i have below xml file suing tcl scripting language.

<workarea>
  <poller name="Poller1">
    <pollerAttribute loc="c:\abc" username="abc" password="xxx">
      <value>123</value>
    </pollerAttribute>
  </poller>
  <poller name="Poller2">
    <pollerAttribute loc="c:\def" username="def" password="xxx">
      <value>345</value>
    </pollerAttribute>
  </poller>
  .....
</workarea>

here i want to read the each tage with Poller name and then change the password="xxx" for that. i am new to tcl scripting language. any help will be great for me. thanks in adavance.

Upvotes: 3

Views: 10488

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

By far the easiest way of doing this with Tcl is by using tDOM to manipulate the XML. You use an XPath expression to select the elements whose password attributes you want to alter, and then you can just iterate over those nodes and change them as necessary. Finally, you need to remember that changing the document in memory is not changing the document on disk; reading and writing the serialized document are important steps too.

package require tdom

set filename "thefile.xml"
set xpath {//pollerAttribute[@password]}

# Read in
set f [open $filename]
set doc [dom parse [read $f]]
close $f
set root [$doc documentElement]

# Do the update of the in-memory doc
foreach pollerAttr [$root selectNodes $xpath] {
    $pollerAttr setAttribute password "theNewPassword"
}

# Write out (you might or might not want the -doctypeDeclaration option)
set f [open $filename "w"]
$doc asXML -channel $f -doctypeDeclaration true
close $f

That's about it. (You might need more care with how to select the elements with the right password attributes, and to supply the replacement passwords in a more sophisticated way, but those are finessing.)

Upvotes: 7

Related Questions