我想创建这个xml文件并使其成为可以通过终端修改它并稍后添加新的“日志”条目。
这是修改后我想要的结果:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="hwlog.xslt"?>
<logroot>
<log>
<subject>Maths</subject>
<timestart>12:00</timestart>
<timeend>13:00</timeend>
<timespent>1H</timespent>
<worktype>Exercises</worktype>
<workplace>home</workplace>
</log>
<log>
<subject>Geo</subject>
<timestart>14:00</timestart>
<timeend>15:00</timeend>
<timespent>1H</timespent>
<worktype>Exercises</worktype>
<workplace>home</workplace>
</log>
</logroot>
到目前为止,这是我的python脚本:
from lxml import etree
doc = etree.parse('hwlog.xml')
log = etree.Element("log")
subject = etree.SubElement(log, "subject")
timestart = etree.SubElement(log, "timestart")
timeend = etree.SubElement(log, "timeend")
timespent = etree.SubElement(log, "timespent")
worktype = etree.SubElement(log, "worktype")
workplace = etree.SubElement(log, "workplace")
titlesubjectinput = input("Subject : ")
titletimestartinput = input("Time Started : ")
titletimeendinput = input("Time Ended : ")
titletimespentinput = input("Time Spent [time ended - time started] : ")
titleworktypeinput = input("Work Type : ")
titleworkplaceinput = input("Work Place : ")
subject.text = titlesubjectinput
timestart.text = titletimestartinput
timeend.text = titletimeendinput
timespent.text = titletimespentinput
worktype.text = titleworktypeinput
workplace.text = titleworkplaceinput
outfile = open("hwlog.xml", "wb")
doc.write(outfile)
虽然当我运行它并输入,例如,(按提示顺序): Geo,14:00,15:00,1H,练习,回家 XML文件如下:
<?xml-stylesheet type="text/xsl" href="hwlog.xslt"?><logroot>
<log>
<subject>Maths</subject>
<timestart>12:00</timestart>
<timeend>13:00</timeend>
<timespent>1H</timespent>
<worktype>Exercises</worktype>
<workplace>home</workplace>
</log>
</logroot>
这显然不是我想要的。我怎样才能让它像我想要的那样出现(第一个XML示例)?
请原谅我可怕的编程技巧,我是一个“菜鸟”。答案 0 :(得分:0)
你必须附加新的log-Element:
from lxml import etree
doc = etree.parse('hwlog.xml')
log = etree.SubElement("log")
etree.SubElement(log, "subject").text = input("Subject : ")
etree.SubElement(log, "timestart").text = input("Time Started : ")
etree.SubElement(log, "timeend").text = input("Time Ended : ")
etree.SubElement(log, "timespent").text = input("Time Spent [time ended - time started] : ")
etree.SubElement(log, "worktype").text = input("Work Type : ")
etree.SubElement(log, "workplace").text = input("Work Place : ")
doc.getroot().append(log)
with open("hwlog.xml", "wb") as outfile:
doc.write(outfile)