简体   繁体   中英

Creating and writing an XML file with Python

I'm newbie to Python. I've searched for hours and hours and can't get a proper answer that works.

I am trying to create an XML from scratch that will be fulfilled with information given by the user, the file will be written to a path chosen by the user.

I've seen many different methods, the only which worked for me without various errors doesn't include pretty print and all the XML is in one line.

What to use to do this please?

Thanks a lot,

The XML file will look like this:

  <?xml version="1.0" encoding="utf-8"?>
    <ScriptTaskDto xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Test" Timeout="00:00:00" Id="4e03bd61-1685-490d-9478-6e73ee4a31e8">
      <Properties>
        <PropertyElementDto Name="User" EvalutionType="User" />
      </Properties>
      <ProjectRepository>UserRepository</ProjectRepository>
      <ProjectName>ProjectName</ProjectName>
      <ProjectVersion Val="1.9.0.0" />
      <ReleaseAllVariablesAtEndTest xsi:nil="true" />
      <Sequence name="sequence" Timeout="00:00:00" Id="d5fdf550-3fcd-4d81-9e0c-dbb8823d6545" NumberOfIteration="1">
        <TaskCollection>
          <SDKRequest name="Name" Description="Description" Timeout="00:00:00" Id="acb231ba-0f96-4308-a6eb-c2ee00fdf102" service="DashboardService" method="xxx" ExpectedDuration="xxx">
            <args>
              <arg xsi:type="xsd:string">Name</arg>
              <arg xsi:type="xsd:float">10</arg>
            </args>
          </SDKRequest>
<SDKRequest name="Name" Description="Description" Timeout="00:00:00" Id="acb231ba-0f96-4308-a6eb-c2ee00fdf102" service="DashboardService" method="xxx" ExpectedDuration="xxx">
            <args>
              <arg xsi:type="xsd:string">Name</arg>
              <arg xsi:type="xsd:float">10</arg>
            </args>
          </SDKRequest>
          <Sleep name="EtapeAttente" Timeout="00:00:00" Id="5b6e68cc-1b6b-43f7-b44b-6e644181bf44" ExpectedDuration="00:00:00" DelayMilliseconds="60000" />
        </TaskCollection>
      </Sequence>
    </ScriptTaskDto>

For pretty format xml and store in file, you can to this:

import xml.dom.minidom
xml_unpretty = "<foo>hello<bar>22</bar></foo>"
xml_pretty = xml.dom.minidom.parseString(xml_unpretty).toprettyxml(indent="    ",encoding="utf8")
myfile = open("foo.xml","w").write(xml_pretty.decode())

Result: file look like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM