#!/usr/bin/env python
# -*- coding: utf-8 -*-
from xml.dom.minidom import parse
import xml.dom.minidom as md

"""gp_data.xml构造
<gp_data>
	<gp>
		<gp_info code='' name=''>
			<upto></upto>
			<downto></downto>
			<note</note>
		</gp_info>
	</gp>
</gp_data>
"""


# read gp_data.xml file, return xml data in list
def read_xml(filename):
    domtree = md.parse(filename)
    de = domtree.documentElement
    gps = de.getElementsByTagName('gp')
    gp_datas = []
    for e in gps:
        gp_info = e.getElementsByTagName('gp_info')[0]
        upto = e.getElementsByTagName('upto')[0]
        downto = e.getElementsByTagName('downto')[0]
        note = e.getElementsByTagName('note')[0]
        if upto.hasChildNodes():
            upto_value = upto.childNodes[0].nodeValue
        else:
            upto_value = ""

        if downto.hasChildNodes():
            downto_value = downto.childNodes[0].nodeValue
        else:
            downto_value = ""

        if note.hasChildNodes():
            note_value = note.childNodes[0].nodeValue
        else:
            note_value = ""

        gp_datas.append(
            [gp_info.getAttribute('name'), gp_info.getAttribute('code'), upto_value, downto_value, note_value, gp_info.getAttribute("hy")])
    return gp_datas


# write data into xml file
def write_xml(filename, data):
    doc = md.Document()
    gp_data = doc.createElement("gp_data")
    doc.appendChild(gp_data)
    for one in data:
        gp = doc.createElement("gp")
        gp_data.appendChild(gp)

        gp_info = doc.createElement("gp_info")
        gp_info.setAttribute("name", one[0])
        gp_info.setAttribute("code", one[1])
        gp_info.setAttribute("hy", one[5])
        gp.appendChild(gp_info)

        upto = doc.createElement("upto")
        upto.appendChild(doc.createTextNode(one[2]))
        gp.appendChild(upto)

        downto = doc.createElement("downto")
        downto.appendChild(doc.createTextNode(one[3]))
        gp.appendChild(downto)

        note = doc.createElement("note")
        note.appendChild(doc.createTextNode(one[4]))
        gp.appendChild(note)


    f = file(filename, "w")
    doc.writexml(f, addindent='	', newl='\n', encoding='utf-8')
    f.close
    return


if __name__ == "__main__":
    data = read_xml("gp_data.xml")
    print data
# write_xml("gp_data.xml", [["制度投资","000676","16.57", "2"],])
