How to replace DOCTYPE element in Python?

How to replace DOCTYPE element in Python?



My input file is:


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<book>
<name>ABC</name>
</book>



I want to change the DOCTYPE element (commented - see below):


DOCTYPE


<?xml version="1.0" encoding="utf-8"?>
<!-- <!DOCTYPE note SYSTEM "Note.dtd"> -->
<book>
<name>ABC</name>
</book>




1 Answer
1



I wonder if we can do xml manipulation. Here what you can do with string manipulation


a='''<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<book>
<name>ABC</name>
</book>'''
lis=a.split('n')
for i,j in zip(lis,range(len(lis))):
if i.startswith('<!DOCTYPE'):
i = '<!--'+i+'-->'
lis[j]=i
a='n'.join(lis)



If it does not have anything to split on.


a='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE note SYSTEM "Note.dtd"><book><name>ABC</name></book>'
str1=""
start=a.index('<!DOCTYPE')
end=a.index('>',start)
str1=a[:start]
str1+='<!--'+'<!DOCTYPE note SYSTEM "Note.dtd">'+'-->'
str1+=a[end+1:]
str1 #'<?xml version="1.0" encoding="utf-8"?><!--<!DOCTYPE note SYSTEM "Note.dtd">--><book><name>ABC</name></book>'






Your answer is work correctly but you know that I want to change doctype element if doctyoe element is coming in third line than your code is fail.

– Anil Kumar Gupta
Sep 13 '18 at 16:12






@AnilKumarGupta see edit.

– mad_
Sep 13 '18 at 16:19






Ok if all element is coming in one line then.

– Anil Kumar Gupta
Sep 13 '18 at 16:36






Then split by space if it is really an xml. Otherwise, edit the question with all the possibilities.

– mad_
Sep 13 '18 at 16:37






Check this code. <?xml version="1.0" encoding="utf-8"?><!DOCTYPE note SYSTEM "Note.dtd"><book><name>ABC</name></book>

– Anil Kumar Gupta
Sep 13 '18 at 16:41




Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế