7

Code:

from lxml import etree

# Create the network XML file tree
root = etree.Element('network')
tree = etree.ElementTree(root)

# Create the nodes data
name = etree.Element('nodes')
root.append(name)
element = etree.SubElement(name, 'node')
element.set('id', '1')

# Create the links data
name = etree.Element('links')
root.append(name)
element = etree.SubElement(name, 'link')
element.set('id', '2')

# Print document to screen
print etree.tostring(root, encoding='UTF-8', xml_declaration=True, pretty_print=True)

Output:

<?xml version='1.0' encoding='UTF-8'?>
<network>
  <nodes>
    <node id="1"/>
  </nodes>
  <links>
    <link id="2"/>
  </links>
</network>

The code above produces this output. However, apart from the declaration which is used as arguments in the tostring() method and printed at the top of the document. I am yet to figure out how to make comments visible if you want them say midway in the document. I have seen earlier posts like this, but it didn't answer my question. Can someone help me with how I can do this:

<?xml version='1.0' encoding='UTF-8'?>
    <network>
      <nodes>
        <node id="1"/>
      </nodes>

         <!-- ==============Some Comment============================= -->
    
      <links>
        <link id="2"/>
      </links>
    </network>
1
  • Please use a more descriptive title. Also, xlmx isn't a thing. Commented Mar 30, 2016 at 22:11

1 Answer 1

15

To insert a comment you can do this, after your code:

comment = etree.Comment(' === Some Comment === ')
root.insert(1, comment)  # 1 is the index where comment is inserted

If you want to add spaces, for instance in the tail of the nodes element, that may mess with prettyprint, because once there is text in tails it won't know where to add whitespace safely. I suppose you could use the same technique as indent, from ElementLib.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.