How to obtain any xml node value using Python

Source: Internet
Author: User

How to obtain any xml node value using Python

This example describes how to obtain the value of any xml node using Python. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

#-*-Coding: UTF-8 -*-

Import xml. dom. minidom

ELEMENT_NODE = xml. dom. Node. ELEMENT_NODE

Class SimpleXmlGetter (object ):

Def _ init _ (self, data ):

If type (data) = str:

Self. root = xml. dom. minidom. parse (data)

Else:

Self. root = data

Def _ getattr _ (self, name): # support. operation

If name = 'data ':

Return self. root. firstChild. data

For c in self. root. childNodes:

If c. nodeType = ELEMENT_NODE and c. tagName = name:

Return SimpleXmlGetter (c)

Def _ getitem _ (self, index): # support [] operation

ENodes = [e for e in self. root. parentNode. childNodes

If e. nodeType = ELEMENT_NODE and e. tagName = self. root. tagName]

Return SimpleXmlGetter (eNodes [index])

Def _ call _ (self, * args, ** kwargs): # support () openration, for query conditions

For e in self. root. parentNode. childNodes:

If e. nodeType = ELEMENT_NODE:

For key in kwargs. keys ():

If e. getAttribute (key )! = Kwargs [key]:

Break

Else:

Return SimpleXmlGetter (e)

If _ name _ = "_ main __":

X = SimpleXmlGetter ("sysd. xml ")

Print x. sysd. sysagent. param [2]. data

Print x. sysd. sysagent. param (name = "querytimeout", type = "second"). data

I hope this article will help you with Python programming.

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.