[Python] python small essay format string and parse xml xml file

1: parse xml --- file

from xml.dom.minidom Import the parse
 Import xml.dom.minidom 

# using Open XML document parser minidom 
DOMTree = xml.dom.minidom.parse ( " ./test.xml " )
 Print (DOMTree) 
Collection = DOMTree.documentElement 


# a label set 
VariationChilds = collection.getElementsByTagName ( " NS2: VariationChild " ) 

# fetch data in the tag set 
for VariationChild in VariationChilds: 
    Asin = VariationChild.getElementsByTagName ( ' ASIN ')[0].childNodes[0].data
    color = VariationChild.getElementsByTagName('ns2:Color')[0].childNodes[0].data
    print(Asin,color)

2: string parsing xml ---

from xml.dom.minidom Import parseString # Import packet parsing strings 

xml_dom = parseString (xml_srt) # where you put the xml data, then converted to xml.dom.minidom.Document objects, the above operation can be carried out,
print (xml_dom)

3: The complete code (integrated use)

= MWSs.make_request xml_data (extra_data, " the POST " ) .original
 Print (xml_data) return xml format data # 

# string into xml.dom.minidom.Document xml_data objects are xml format string 
DOMTree = parseString (xml_data) 

Collection = DOMTree.documentElement
 # collection you want to label 
VariationChilds = collection.getElementsByTagName ( " NS2: VariationChild " ) 

# traverse value 
for VariationChild in VariationChilds: 
    Asin = VariationChild.getElementsByTagName ( ' ASIN ' ) [0] .childNodes [0]. data 
    Color= VariationChild.getElementsByTagName('ns2:Color')[0].childNodes[0].data
    print(Asin,color)

Guess you like

Origin www.cnblogs.com/wanghong1994/p/12123631.html