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>'
@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.
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