Created
September 12, 2021 18:20
-
-
Save konradish/a4cc08948e90448d49bf8575148b2432 to your computer and use it in GitHub Desktop.
Flatten XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/46299727/flatten-xml-document-in-java | |
from org.w3c.dom import Document | |
from org.w3c.dom import Node | |
from org.xml.sax import InputSource | |
from java.io import StringReader | |
from java.util import Properties | |
from javax.xml.parsers import DocumentBuilder | |
from javax.xml.parsers import DocumentBuilderFactory | |
def xmlToProps(strXML): | |
def flattenXML(currentPath, currentNode, props): | |
if currentNode.nodeType == Node.TEXT_NODE and currentNode.nodeValue: | |
props[currentPath]=currentNode.nodeValue | |
else: | |
childNodes = currentNode.childNodes | |
length = childNodes.length | |
nextPath = currentNode.nodeName if not currentPath else currentPath + '.' + currentNode.nodeName | |
for i in range(length): | |
item = childNodes.item( i ) | |
flattenXML( nextPath, item, props ) | |
return props | |
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(strXML))) | |
root = document.getDocumentElement() | |
d = {} | |
props = Properties() | |
flattenXML("", root, d) | |
for k,v in d.items(): | |
props.setProperty(k,v) | |
return props | |
# str_xml = open('c:/temp/test.xml').read() | |
# props = xmlToProps(str_xml) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment