Python reads xml files

Source: Internet
Author: User

There are many articles about reading xml from python, but most of them post an xml file and then post the code for processing the file. This is not conducive to learning for beginners. I hope this article will be easier to understand and teach you how to use python to read xml files. What is xml? Xml can be used to tag data and define data types. It is a source language that allows you to define your own markup language. Abc. xml copy Code <? Xml version = "1.0" encoding = "UTF-8"?> <Catalog> <maxid> 4 </maxid> <login username = "pytest" passwd = '000000'> <caption> Python </caption> <item id = "4"> <caption> test </caption> </item> </login> <item id = "2"> <caption> Zope </caption> </item> </catalog> copy code OK, in terms of structure, it is similar to our common HTML hypertext markup language. However, they are designed for different purposes. hypertext markup language is designed to display data, and its focus is on the appearance of the data. It is designed to transmit and store data, with the focus on data content. It has the following features: First, it consists of tag pairs. The <aa> </aa> tag can have attributes: <aa id = '000000'> </aa> the tag pair can be embedded with data: <aa> abc </aa> tags can be embedded with sub-tags (with hierarchical relationships ): <aa> <bb> </aa> to obtain tag attributes, the following describes how to use python to read these types of files. Copy Code # coding = utf-8import xml. dom. minidom # Open the xml document dom = xml. dom. minidom. parse ('abc. xml ') # obtain the document Element Object root = dom.doc umentElementprint root. nodeNameprint root. nodeValueprint root. nodeTypeprint root. ELEMENT_NODE: copy the code mxl. dom. the mini-dom module is used to process xml files. Therefore, we need to introduce it first. Xml. dom. minidom. parse () is used to open an xml file and change the dom variable of the file object. DocumentElement is used to obtain the document elements of a dom object and give the obtained object to each root node with its nodeName, nodeValue, and nodeType attributes. NodeName is the node name. NodeValue is the value of a node and is only valid for text nodes. NodeType is the node type. Catalog is of the ELEMENT_NODE type. The following types are available: 'attribute _ node' 'cdata _ section_node' 'comment _ node' 'document _ fragment_node' 'document _ node' 'document _ type_node' 'element _ node' 'entity _ node' 'entity _ REFERENCE_NODE ''notation _ node' 'processing _ INSTRUCTION_NODE ''TEXT _ node' NodeTypes-famous constant http://www.w3school.com.cn/xmldom/dom_nodetype.asp get sub-tags now get the tag name replication for the sub-tag of catalog code <? Xml version = "1.0" encoding = "UTF-8"?> <Catalog> <maxid> 4 </maxid> <login username = "pytest" passwd = '000000'> <caption> Python </caption> <item id = "4"> <caption> test </caption> </item> </login> <item id = "2"> <caption> Zope </caption> </item> </catalog> copy the code for the child element that knows the element name, you can use the getElementsByTagName method to get: copy the Code # coding = utf-8import xml. dom. minidom # Open the xml document dom = xml. dom. minidom. parse ('abc. xml ') # obtain the document Element Object root = dom.doc umentElement bb = root. getElementsByTagNa Me ('maxid') B = bb [0] print B. nodeName bb = root. getElementsByTagName ('login') B = bb [0] print B. how does nodeName copy Code differentiate tags with the same Tag Name: Copy Code <? Xml version = "1.0" encoding = "UTF-8"?> <Catalog> <maxid> 4 </maxid> <login username = "pytest" passwd = '000000'> <caption> Python </caption> <item id = "4"> <caption> test </caption> </item> </login> <item id = "2"> <caption> Zope </caption> </item> </catalog> how do I distinguish between the <caption> and <item> code copy labels? Copy Code # coding = utf-8import xml. dom. minidom # Open the xml document dom = xml. dom. minidom. parse ('abc. xml ') # obtain the document Element Object root = dom.doc umentElement bb = root. getElementsByTagName ('caption ') B = bb [2] print B. nodeName bb = root. getElementsByTagName ('item') B = bb [1] print B. nodeName copy code root. getElementsByTagName ('caption ') obtains a group of caption tags. B [0] indicates the first tag in A group. B [2], the third tag in the group. Copy code for obtaining tag property values <? Xml version = "1.0" encoding = "UTF-8"?> <Catalog> <maxid> 4 </maxid> <login username = "pytest" passwd = '000000'> <caption> Python </caption> <item id = "4"> <caption> test </caption> </item> </login> <item id = "2"> <caption> Zope </caption> </item> </catalog> duplicate codes <login> and <item> labels have attributes, how to obtain their attributes? Copy Code # coding = utf-8import xml. dom. minidom # Open the xml document dom = xml. dom. minidom. parse ('abc. xml ') # obtain the document Element Object root = dom.doc umentElement itemlist = root. getElementsByTagName ('login') item = itemlist [0] un = item. getAttribute ("username") print unpd = item. getAttribute ("passwd") print pd ii = root. getElementsByTagName ('item') i1 = ii [0] I = i1.getAttribute ("id") print I i2 = ii [1] I = i2.getAttribute ("id ") print I copy the code getAttribute Method to obtain the value corresponding to the attribute of the element. Obtain the data replication code between tag pairs <? Xml version = "1.0" encoding = "UTF-8"?> <Catalog> <maxid> 4 </maxid> <login username = "pytest" passwd = '000000'> <caption> Python </caption> <item id = "4"> <caption> test </caption> </item> </login> <item id = "2"> <caption> Zope </caption> </item> </catalog> copy the Code <caption> there is data between tag pairs, how to obtain the data? There are multiple methods to obtain the data between tag pairs, method 1 copy Code # coding = utf-8import xml. dom. minidom # Open the xml document dom = xml. dom. minidom. parse ('abc. xml ') # obtain the document Element Object root = dom.doc umentElement cc = dom. getElementsByTagName ('caption ') c1 = cc [0] print c1.firstChild. data c2 = cc [1] print c2.firstChild. data c3 = cc [2] print c3.firstChild. the data Replication code firstChild attribute returns the first child node of the selected node ,. data indicates that data of the node owner is obtained. Method 2 copy the Code # coding = utf-8from xml. etree import ElementTree as ETper = ET. parse ('abc. xml ') p = per. findall ('. /login/item ') for oneper in p: for child in oneper. getchildren (): print child. tag, ':', child. text p = per. findall ('. /item') for oneper in p: for child in oneper. getchildren (): print child. tag, ':', child. the method 2 of text copy code is a bit complicated, and the referenced module is also different from the previous one. findall is used to specify the level of tag to start traversing. The getchildren method returns all child tags in the document order. And output the tag Name (child. tag) and tag data (child. text)

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.