Home Backend Development Python Tutorial Detailed explanation of python xml parsing examples

Detailed explanation of python xml parsing examples

Dec 14, 2016 pm 06:00 PM
xml parsing

python xml parsing

first.xml

<info> 
<person > 
<id>1</id> 
<name>fsy</name> 
<age >24</age> 
</person> 
<person> 
<id>2</id> 
<name>jianjian</name> 
<age>24</age> 
</person> 
<count id =&#39;1&#39;>1000</count> 
</info>
Copy after login

from xml.etree import ElementTree as etree

Read in

def read_xml(file): 
# parse()函数会返回一个能代表整篇文档的对象。这不是根元素。要获得根元素的引用可以调用getroot()方法。 
tree = etree.parse(file) 
root = tree.getroot() 
return root
Copy after login

Get information

def print_node(node): 
&#39;&#39;&#39;&#39;&#39;打印结点基本信息&#39;&#39;&#39; 
print("node.tag:%s" % node.tag) 
print("node.attrib:%s"%node.attrib) 
print( "node.text:%s" % node.text)
Copy after login

Search:

find_all 
>>> root = read_xml (&#39;first.xml&#39;)   
>>> res = root.findall("person") 
[<Element &#39;person&#39; at 0x00000000033388B8>, <Element &#39;person&#39; at 0x0000000003413D68>] 
   
注意:findall只查询直接的子节点 
>>> r1 = root.findall("id") 
>>> r1 
[] 
>>> r =tree.findall(".//id") 
>>> for e in r: 
  print( e,e.text) 
      
<Element &#39;id&#39; at 0x00000000034279F8> 1 
<Element &#39;id&#39; at 0x0000000003427B38> 2
Copy after login

find:

#find()方法用来返回第一个匹配到的元素。当我们认为只会有一个匹配,或者有多个匹配但我们只关心第一个的时候,这个方法是很有用的。 
>>> res[0].find("id") 
<Element &#39;id&#39; at 0x0000000003413CC8> 
>>> print_node(res[0].find("id")) 
node.tag:id 
node.attrib:{} 
node.text:1
Copy after login

find find Failure:

When using find, please note that in a Boolean context, if the ElementTree element object does not contain child elements, its value will be considered False (that is, if len(element) is equal to 0). This means if element.find('...') is not testing whether the find() method found a match; this statement is testing whether the matched element contains child elements. If you want to test whether the find() method returns an element, you need to use if element.find('...') is not None.

>>> bk = res[0].find("no") 
>>> bk 
>>> type(bk) 
<class &#39;NoneType&#39;> 
>>> res[0].find("id") 
<Element &#39;id&#39; at 0x0000000003413CC8> 
>>> if res[0].find("id"): 
    print("find") 
  else: 
    print("not find") 
not find 
>>> if res[0].find("id") is not None: 
    print("find") 
  else: 
    print("not find") 
find
Copy after login

The above is a detailed explanation of python xml parsing examples. Thank you for reading. I hope it can help everyone. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Use Gin framework to implement XML and JSON data parsing functions Use Gin framework to implement XML and JSON data parsing functions Jun 22, 2023 pm 03:14 PM

In the field of web development, XML and JSON, one of the data formats, are widely used, and the Gin framework is a lightweight Go language web framework that is simple, easy to use and has efficient performance. This article will introduce how to use the Gin framework to implement XML and JSON data parsing functions. Gin Framework Overview The Gin framework is a web framework based on the Go language, which can be used to build efficient and scalable web applications. The Gin framework is designed to be simple and easy to use. It provides a variety of middleware and plug-ins to make the development

Java Error: XML Parsing Error, How to Fix and Avoid Java Error: XML Parsing Error, How to Fix and Avoid Jun 24, 2023 pm 05:46 PM

As Java becomes more and more widely used in the Internet field, many developers may encounter the problem of "XML parsing error" when using XML for data parsing. XML parsing error means that when using Java to parse XML data, the program cannot parse the data normally due to incorrect data format, unclosed tags, or other reasons, thus causing errors and exceptions. So, how should we solve and avoid when facing XML parsing errors? This article will explain this issue in detail. 1. XML parsing

How to solve the problem of high memory usage of XML parsing in Java development How to solve the problem of high memory usage of XML parsing in Java development Jun 29, 2023 am 09:37 AM

XML is a commonly used data exchange format. In Java development, large-scale XML files often need to be parsed. However, since XML files often contain a large number of nodes and elements, traditional XML parsing methods can easily lead to high memory usage. This article will introduce some methods to solve the problem of high memory usage of XML parsing. Using the SAX parser SAX (SimpleAPI for XML) is an event-driven XML parsing method. Compared to DOM (DocumentO

How to use PHP to parse XML and obtain node content How to use PHP to parse XML and obtain node content Jun 13, 2023 pm 04:31 PM

When developing web applications, XML is a very important data format that can be used in scenarios such as data exchange and information sharing. In PHP, we can use built-in functions and third-party libraries to parse and manipulate XML. Below we will discuss how to use PHP to parse XML and obtain the content of the nodes in it. Parse XML files First, we need to parse XML files. PHP provides two main methods to parse XML: 1.1. Using SimpleXML SimpleXML is within PHP

PHP8.1 update: enhanced XML parsing capabilities PHP8.1 update: enhanced XML parsing capabilities Jul 07, 2023 am 09:22 AM

PHP8.1 update: Enhanced XML parsing function With the rapid development of the Internet, XML (Extensible Markup Language) plays an important role in data exchange and information transmission. As a universal data format, XML is often used to transfer and store data between different applications. In order to provide better XML parsing capabilities, PHP8.1 has enhanced the XML parsing function to provide developers with more convenience. In PHP8.1, an important improvement is the introduction of libxml_disabl

Solution to solve Java XML parsing exception (XMLParsingException) Solution to solve Java XML parsing exception (XMLParsingException) Aug 19, 2023 pm 01:43 PM

Solution introduction to solving Java XML parsing exceptions (XMLParsingException): When processing XML files, we often encounter XML parsing exceptions (XMLParsingException). This is caused by XML file format errors or incorrect XML parser configuration. This article will introduce some common XML parsing exceptions and solutions to help developers better deal with these problems. 1. The cause of XML parsing exception is parsing XML document.

How to reduce XML parsing memory usage in Java development How to reduce XML parsing memory usage in Java development Jun 30, 2023 pm 09:19 PM

How to solve the problem of XML parsing occupying too much heap memory in Java development Introduction: With the explosive growth of information and data, the importance of XML (Extensible Markup Language) in enterprise application development continues to increase. However, you may encounter problems with excessive heap memory usage during XML parsing, especially when dealing with large XML files. This article will introduce some methods and techniques to solve this problem. 1. Understand the XML parsing process. Before we deeply solve the problem of XML parsing occupying too much heap memory, we first understand the basics of XML parsing.

How to handle XML parsing errors in PHP? How to handle XML parsing errors in PHP? Dec 02, 2023 pm 02:58 PM

PHP is a widely used programming language that supports many different file formats, including XML. When processing XML files, parsing errors may occur. This article will explain how to handle XML parsing errors in PHP and provide some concrete code examples. Checking XML File Format Before processing an XML file, you must ensure that the XML file is in the correct format. The XML file must be in a strict format, otherwise the parser will not be able to process the file. For example, the XML file must contain the root element and use the correct namespace,

See all articles