1

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>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Irianeth
  • 11
  • 3
  • 3
    _the only wich worked for me without various errors doesnt include pretty print and all the XML is in one line._: Please share your code. – Maurice Meyer Aug 08 '22 at 13:18
  • 1
    If the specific problem is pretty-printing, I'm inclined to close as duplicate of https://stackoverflow.com/q/749796/407651 – mzjn Aug 08 '22 at 15:31

1 Answers1

1

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