Python processing XML

Source: Internet
Author: User

Python processing XML python xml

      • Read XML
        • Get DOM Object
        • Get Document Object
        • Node properties
        • Access to child nodes
        • Text node
        • Get Node Properties
        • Summary: Use Minidom to read the information in XML
      • Edit XML
        • Generating DOM objects
        • To display the generated XML content
        • Get root element
        • element to add child elements and element attributes
        • Generate CDATA Nodes
        • XML Import to File

Read XML get DOM object

The DOM is a Document Object Model short name, it is a method of representing an XML document in an object tree, and the advantage of using it is that you can traverse the object very flexibly.

    1. Method One:

fromimport minidomdom = minidom.parse("e:\test.xml")
    1. Method Two:

fromimport minidomf = open("e:\test.xml"‘r‘)dom = minidom.parse("e:\test.xml")
Get Document Object

Get the root element:

root = dom.documentElement
Node properties

Each node has its nodeName , nodeValue nodeType attributes. nodeNameis the node name. nodeValueis the value of the element and is valid only for the text node, which is the type of the nodeType node (integer constant).

‘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‘
root.nodeName   #根元素的名字root.nodeType   #根元素的节点类型root.nodeValue  #根元素的值,只对文本结点有效
Access to child nodes
    1. How to use getElementsByTagName
      getElementsByTagNamemethod returns a list. (By searching all levels of elements, find tagname for the list of all elements of the given string)
      Statement:root.getElementsByTagName(‘title‘)
      Results: [ ] .

    2. childNodesProperty
      childNodesproperty returns all the immediate child nodes and immediate child elements of a node. That is childNodes , only the first-level child nodes of the current element are saved .
      Statement:root.childNodes
      Results: [ , ] .

Example: Print all direct child element names of the root element

forin root.childNodes:    if node.nodeType == node.ELEMENT_NODE:        print node.nodeName
Text node

Gets the text content of the text node that can be used: data properties
Example:

elements = root.getElementsByTagName("title")forin elements:    forin x.childNodes:        if y.nodeType == y.TEXT_NODE:            print y.data
Get Node Properties

getAttributeMethod gets the node properties.

nodes = root.getElementsByTagName("book")forin nodes:    print x.getAttribute("id")
Summary: Use Minidom to read the information in XML
    1. Import the Xml.dom.minidom module to generate DOM objects

    2. Get Document Object (Root object)

    3. Find the element to process through the getElementsByTagName () method and the ChildNodes property (there are some other methods and properties)

    4. Gets the content of the text node under the element

To edit an XML build DOM object
fromimport minidomimp = minidom.getDOMImplementation()dom = imp.createDocument(None‘booklist‘None)
To display the generated XML content
dom.toxml()
Get root element
root = dom.documentElement
element to add child elements and element attributes
root = dom.documentElementbook = dom.createElement("book")book.setAttribute("id""011")text = dom.createTextNode("my book is from England!")book.appendChild(text)root.appendChild(book)dom.toxml()dom.toprettyxml()
Generate CDATA Nodes
data = dom.createCDATASection("content\nmyContent")root.appendChild(data)root.toxml()

Results:

 \n<booklist>\n\t<book id="011">my book is from England! book>\ncontent\nmyContent booklist>\n
XML Import to File
f = open(r‘e:\text.xml‘,‘w‘)dom.writexml(f)

He Guangfu (heguangfu)@2015-9-17

Python processing XML

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.