-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxmlReader.py
More file actions
executable file
·63 lines (51 loc) · 1.64 KB
/
xmlReader.py
File metadata and controls
executable file
·63 lines (51 loc) · 1.64 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
# encoding: UTF-8
from xml.etree import ElementTree as ET
import os
class XmlHandler:
def __init__(self, xmlfile):
print ("xmlHandler init: " + xmlfile)
self.xmlTree = self.readXml(xmlfile)
def readXml(self, in_path):
if not os.path.exists(in_path):
print ("there is no such file: " + in_path)
sys.exit()
try:
tree = ET.parse(in_path)
except:
print ("tree parse error")
print ("return tree successfully")
return tree
def getNodes(self, tree):
root = tree.getroot()
print ("return root successfully")
return root.getchildren()
def findNode(self, nodes, tag):
for node in nodes:
if node.tag == tag:
return node
def getTexts(self, nodes, tags):
texts = []
for tag in tags:
texts.append(self.findNode(nodes, tag).text)
return texts
def read(self):
nodes = self.getNodes(self.xmlTree)
host, port, path, timestamp, offset= self.getTexts(nodes, ["host", "port", "path", "timestamp", "offset"])
return host, port, path, timestamp, offset
def writeXml(self, node, text):
node.text = text
#print node.tag, node.text
def setTexts(self, texts, tags):
nodes = self.getNodes(self.xmlTree)
for text, tag in zip(texts, tags):
self.writeXml(self.findNode(nodes, tag), text)
def write(self, newTimestamp, newOffset, xmlfile):
#int "time is " + newTimestamp
self.setTexts([newTimestamp, newOffset], ["timestamp", "offset"])
self.xmlTree.write(xmlfile, encoding="utf-8")
if __name__ == '__main__':
xmlHandler = XmlHandler("client_config.xml")
print xmlHandler.read()
#xmlHandler.write("newTimestamp", "newOffset", "client_config.xml")
print xmlHandler.read()