domtclactivestateactivetcl

How to add data to an element with ActiveState's dom package


In TCL, if you use the DOM package (available in the ActiveState distribution) you can create an xml.

set xmlDoc [::dom::create]
set root [::dom::document createElement $xmlDoc "trafficStatistics"]

set statElement [::dom::document createElement $root "Tx_Frames"]
::dom::element setAttribute $statElement "type" "numericlist"
::dom::element setAttribute $statElement "displayName" "Tx Frames"

puts [::dom::serialize $xmlDoc -indent true]

creating this simple xml:

<result>
    <trafficStatistics type="structure">
        <Tx_Frames type="numericlist" displayName="Tx Frames"></Tx_Frames>
    </trafficStatistics>
</result>

How can I add some data to the Tx_Frames element?

<Tx_Frames type="numericlist" displayName="Tx Frames">some data</Tx_Frames>

Note that the dom package is actually a wrapper over libxml2


Solution

  • I believe you want the ::dom::document createTextNode command. For example:

    ::dom::document createTextNode $statElement "some data"
    

    When I add this command to your sample script:

    set xmlDoc [::dom::create]
    set root [::dom::document createElement $xmlDoc "trafficStatistics"]
    
    set statElement [::dom::document createElement $root "Tx_Frames"]
    ::dom::element setAttribute $statElement "type" "numericlist"
    ::dom::element setAttribute $statElement "displayName" "Tx Frames"
    ::dom::document createTextNode $statElement "some data"
    

    It produces this XML:

    <trafficStatistics>
      <Tx_Frames type="numericlist" displayName="Tx Frames">some data</Tx_Frames>
    </trafficStatistics>
    

    You can find documentation for the dom package here:

    http://docs.activestate.com/activetcl/8.5/tcldom/index.html

    Hope that helps,

    Eric Melski