Python+selenium Automated Software Testing (12th): Python reads and writes XML documents

Source: Internet
Author: User

XML Extensible Markup Language, which can be used to tag data, define data types, is a source language that allows users to define their own markup language.
XML has the following characteristics: First, it is tagged to the constituent:<aa></aa> tag can have attributes: <aa id= ' 123 ' ></aa> tag pair can embed data: <AA>ABC</AA >
Python often has several modules for XML document reading and writing:
(1) Xml.etree.ElementTree
ElementTree is like a lightweight dom, with a convenient and friendly API. Good code availability, fast speed, low memory consumption.
(2) xml.dom.*
Parses XML data into a tree in memory, manipulating the XML by manipulating the tree.
(3) xml.sax.*

The Python standard library contains the SAX parser, which uses the event-driven model to process XML files by triggering events and invoking user-defined callback functions during parsing of XML.


Writing to an XML document

#Coding:utf-8 fromXml.domImportMinidom#ways to write XML documentsdefcreate_xml_test (filename):#new XML Document ObjectXml=Minidom. Document ()#Create the first node, the first node is the root nodeRoot=xml.cneateelement ('Root')    #Write Property (Xmlns:xsi is a namespace and can also be written to xsi:schemalocation specify an XSD file)Root.setattribute ('Xmlns:xsi', 'http://www.xxx.com')    #After you create a node, you also need to add it to the document before it is validXml.appendchild (Root)#The general root node is rarely write text content, then create a child node for the root nodeText_node=xml.createelement ('element') Text_node.setattribute ('ID','ID1') Root.appendchild (Text_node)#add text to this node, and the text is a nodeText=xml.cneatetextnode ('Hello World') text_node.appendchild (text)#once a node has been added to the text, you can continue to append something elseTag=xml.createelement ('Tag') Tag.setattribute ('Data','Tag Data') Text_node.appendchild (tag)#Once you've written it, you'll need to save the document.F=open (filename,'W') F.write (Xml.toprettyxml (Encodings'Utf-8') ) F.close ()if __name__=='__main__':    #under current directory, create 1. XMLCreate_xml_test ('1.xml')

A copy of the XML document will be generated locally

Reading an XML document

#Coding:utf-8 fromXml.domImportMinidom#ways to read XML documentsdefread_xml_test (filename):#Open this document and parse it with the parse methodXML =minidom.parse (filename)#Get root nodeRoot =xml.documentelement#get all element nodes below the root node   #More methods can refer to the content of W3school or with Dir (root) to obtainelements = Root.getelementsbytagname ('element')   #traversal processing, elements is a list    forElementinchelements:#determine if there is an id attribute      ifElement.hasattribute ('ID'):         #you can not add the above judgment, if the property is not found, then return an empty         Print 'ID:, Element.getattribute ('Id')   #traversing the child nodes of element    forNodeinchElement.childnodes:#determine whether text is by Nodemame      ifNode.nodename = ='#text':         #get text content with the Data propertyText = Node.data.replace ('\ n,"')         #the text here needs special treatment, there will be extra \ n         PrintU'\ t Text:', TextElse:         #Output Node name         Print '\ t'+Node.nodename#output attribute values, which can be obtained using the GetAttribute method         #can also be traversed to get that this is a dictionary          forAttr,attr_valinchNode.attributes.items ():Print '\t\t', attr,':'Jattr_valPrint "'if __name__=='__main__': Read_xml_test ('Test.xml') Raw_input ('OK')

Python+selenium Automated Software Testing (12th): Python reads and writes XML documents

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.