substitution for ms xml dom object

Marko Faldix marko.faldix.tudisweck at mplusr.de
Thu Nov 27 10:37:05 EST 2003


Hello,

I have got some standard problems still realized with MS xml 4. The
following code runs on Windows machines with python and win32com installed.

Could you use pyxml or 4suite to make every of these problems work on any
machine?

The standard problems are:

- Selecting many nodes with xPath
- Select a single node with xPath
- Append a child (to selected single node)

Here's the working code:


import win32com.client

class myTest:
    def __init__(self):
        self.xmlString = """<?xml version="1.0"?>
        <wanted>
            <item id="1">Mister X</item>
            <item id="2">Mister Y</item>
            <item id="3">Mister Z</item>
        </wanted>
        """

        print "Our test data is:"
        print self.xmlString

        self.Dom =
win32com.client.dynamic.Dispatch('Msxml2.DOMDocument.4.0')
        self.Dom.loadXML(self.xmlString)

    def Problem_1(self):
        "'First problem: Selecting many nodes with xPath'"

        xPath = "//item"

        nodes = self.Dom.selectNodes(xPath)

        for node in nodes:
            print node.getAttribute("id") + ": " + node.text


    def Problem_2(self):
        "'Second problem: Select a single node with xPath'"

        xPath = "//item[@id='2']"

        node = self.Dom.selectSingleNode(xPath)

        print node.getAttribute("id") + ": " + node.text


    def Problem_3(self):
        "'Third problem: Append a child'"

        xPath = "/wanted"
        parentNode = self.Dom.selectSingleNode(xPath)

        childNode = self.Dom.createElement("item")
        childNode.setAttribute("id", "4" )
        childNode.text = "Mister No"

        parentNode.appendChild(childNode)


test = myTest()

print test.Problem_1.__doc__
test.Problem_1()

print
print test.Problem_2.__doc__
test.Problem_2()

print
print test.Problem_3.__doc__
test.Problem_3()

print "result of Problem_3:"
print test.Dom.xml


Thanks for discussion,

--
Marko Faldix






More information about the Python-list mailing list