Search code examples
python-3.xxmlparsingminidom

text from element in minidom


I have an xml file that has multiple tags PropertySetProperty similar to below:

      <PropertySetProperty xsi:type="typens:PropertySetProperty">
        <Key>PackageIsPublic</Key>
        <Value xsi:type="xs:string">false</Value>
      </PropertySetProperty>

On several of these I need to parse the document and change the Value (for example from false to true).

Here is my current code to test that I have the right elements:

Import xml.dom.minidom as DOM
def changeProps(sddraftPath):
    # Read the sddraft xml.
    doc = DOM.parse(sddraftPath)
    properties = doc.getElementsByTagName('PropertySetProperty')
    for property in properties:
        key = property.firstChild.firstChild.data
        value = property.firstChild.nextSibling.data
        print(key, value)

when I call the function, the "value" line throws the following error:

 "AttributeError: 'Element' object has no attribute 'data'"

if I remove the attribute 'data' I get (for example) the printed result:

PackageIsPublic <DOM Element: Value at 0x1d8e7ebe310>

If I replace data with nodeValue the result is PackageIsPublic None So the code is finding the "value" tag, but doesn't recognize that there is data in it. But it DOES recognize the data in the "key" tag. Any Idea what's going on here!! Any help please!

What I want to get is the actual text in the tag:

PackageIsPublic false

Solution

  • Okay, so playing around with it after posting question (and of course playing around with it before posting didn't yield results) I have figured this out. I needed to add firstChild to the value tag to get the text element: value = property.firstChild.nextSibling.firstChild.data