Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8712051
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T05:01:45+00:00 2026-06-13T05:01:45+00:00

I’m using python’s lxml and I’m trying to read an xml document, modify and

  • 0

I’m using python’s lxml and I’m trying to read an xml document, modify and write it back but the original doctype and xml declaration disappears. I’m wondering if there’s an easy way of putting it back in whether through lxml or some other solution?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T05:01:46+00:00Added an answer on June 13, 2026 at 5:01 am

    tl;dr

    # adds declaration with version and encoding regardless of
    # which attributes were present in the original declaration
    # expects utf-8 encoding (encode/decode calls)
    # depending on your needs you might want to improve that
    from lxml import etree
    from xml.dom.minidom import parseString
    xml1 = '''\
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE root SYSTEM "example.dtd">
    <root>...</root>
    '''
    xml2 = '''\
    <root>...</root>
    '''
    def has_xml_declaration(xml):
        return parseString(xml).version
    def process(xml):
        t = etree.fromstring(xml.encode()).getroottree()
        if has_xml_declaration(xml):
            print(etree.tostring(t, xml_declaration=True, encoding=t.docinfo.encoding).decode())
        else:
            print(etree.tostring(t).decode())
    process(xml1)
    process(xml2)
    

    The following will include the DOCTYPE and the XML declaration:

    from lxml import etree
    from StringIO import StringIO
    
    tree = etree.parse(StringIO('''<?xml version="1.0" encoding="iso-8859-1"?>
     <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "eggs"> ]>
      <root>
       <a>&tasty;</a>
     </root>
    '''))
    
    docinfo = tree.docinfo
    print etree.tostring(tree, xml_declaration=True, encoding=docinfo.encoding)
    

    Note, tostring does not preserve the DOCTYPE if you create an Element (e.g. using fromstring), it only works when you process the XML using parse.

    Update: as pointed out by J.F. Sebastian my assertion about fromstring is not true.

    Here is some code to highlight the differences between Element and ElementTree serialization:

    from lxml import etree
    from StringIO import StringIO
    
    xml_str = '''<?xml version="1.0" encoding="iso-8859-1"?>
     <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "eggs"> ]>
      <root>
       <a>&tasty;</a>
     </root>
    '''
    
    # get the ElementTree using parse
    parse_tree = etree.parse(StringIO(xml_str))
    encoding = parse_tree.docinfo.encoding
    result = etree.tostring(parse_tree, xml_declaration=True, encoding=encoding)
    print "%s\nparse ElementTree:\n%s\n" % ('-'*20, result)
    
    # get the ElementTree using fromstring
    fromstring_tree = etree.fromstring(xml_str).getroottree()
    encoding = fromstring_tree.docinfo.encoding
    result = etree.tostring(fromstring_tree, xml_declaration=True, encoding=encoding)
    print "%s\nfromstring ElementTree:\n%s\n" % ('-'*20, result)
    
    # DOCTYPE is lost, and no access to encoding
    fromstring_element = etree.fromstring(xml_str)
    result = etree.tostring(fromstring_element, xml_declaration=True)
    print "%s\nfromstring Element:\n%s\n" % ('-'*20, result)
    

    and the output is:

    --------------------
    parse ElementTree:
    <?xml version='1.0' encoding='iso-8859-1'?>
    <!DOCTYPE root SYSTEM "test" [
    <!ENTITY tasty "eggs">
    ]>
    <root>
       <a>eggs</a>
     </root>
    
    --------------------
    fromstring ElementTree:
    <?xml version='1.0' encoding='iso-8859-1'?>
    <!DOCTYPE root SYSTEM "test" [
    <!ENTITY tasty "eggs">
    ]>
    <root>
       <a>eggs</a>
     </root>
    
    --------------------
    fromstring Element:
    <?xml version='1.0' encoding='ASCII'?>
    <root>
       <a>eggs</a>
     </root>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.