Reputation: 61
I have an XML string that I've already created from a dict:
from xml.dom import minidom
from dict2xml import dict2xml
s = {
'HierarchyNode': {
'levelid': '2'
}
}
xml = dict2xml(s)
print(xml)
Output:
<HierarchyNode>
<levelid>2</levelid>
</HierarchyNode>
But I'm trying to add it into XML which has already been built (under the read element)
from xml.dom import minidom
from dict2xml import dict2xml
s = {
'HierarchyNode': {
'levelid': '2'
}
}
xml = dict2xml(s)
print(xml)
doc = minidom.Document()
# request
request = doc.createElement('request')
doc.appendChild(request)
# read
read = doc.createElement('Read')
request.appendChild(read)
# inner payload
read.appendChild(xml)
pretty_xml_str = doc.toprettyxml(indent=" ")
print(pretty_xml_str)
Output:
Traceback (most recent call last):
File "c:\Users\Desktop\working_dir\test.py", line 26, in <module>
read.appendChild(xml)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\xml\dom\minidom.py", line 115, in appendChild
if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
AttributeError: 'str' object has no attribute 'nodeType'
I can't append it as a text node because the text node strips the characters.
Upvotes: 0
Views: 914
Reputation: 61
I've discovered there's something called importNode. This allows the xml string being passed in through parseString to be copied to the dom.
from xml.dom import minidom
from xml.dom.minidom import parseString
from dict2xml import dict2xml
s = {
'HierarchyNode': {
'levelid': '2'
}
}
xml = dict2xml(s)
# print(xml)
doc = minidom.Document()
# request
request = doc.createElement('request')
doc.appendChild(request)
# read
read = doc.createElement('Read')
request.appendChild(read)
# inner payload being read in
payload = parseString(xml)
# import payload into doc, and append to read element
x = doc.importNode(payload.childNodes[0], deep=True)
read.appendChild(x)
pretty_xml_str = doc.toprettyxml(indent=" ")
print(pretty_xml_str)
Output:
<?xml version="1.0" ?>
<request>
<Read>
<HierarchyNode>
<levelid>2</levelid>
</HierarchyNode>
</Read>
</request>
Upvotes: 1