xml.etree

How to insert namespace and prefixes into an XML string with Python?

笑着哭i 提交于 2019-11-28 14:04:25
Suppose I have an XML string: <A> <B foo="123"> <C>thing</C> <D>stuff</D> </B> </A> and I want to insert a namespace of the type used by XML Schema, putting a prefix in front of all the element names. <A xmlns:ns1="www.example.com"> <ns1:B foo="123"> <ns1:C>thing</ns1:C> <ns1:D>stuff</ns1:D> </ns1:B> </A> Is there a way to do this (aside from brute-force find-replace or regex) using lxml.etree or a similar library? mzjn I don't think this can be done with just ElementTree. Manipulating namespaces is sometimes surprisingly tricky. There are many questions about it here on SO. Even with the more

how to create a sub-element through variable in python 3.6.5

人走茶凉 提交于 2019-11-28 10:26:56
问题 My code is: import xml.etree.ElementTree as ET from lxml import etree var1 = '<name>This is my text</name>' page = etree.Element('first') doc = etree.ElementTree(page) second = etree.SubElement(page, 'second') second.text = var1 doc.write('a.xml', xml_declaration=True, encoding='utf-8') My output is: <?xml version='1.0' encoding='UTF-8'?> <first><second><name>This is my text</name></second></first> My Desired Output is: <?xml version='1.0' encoding='UTF-8'?> <first><second><name>This is my

How to insert namespace and prefixes into an XML string with Python?

℡╲_俬逩灬. 提交于 2019-11-27 08:16:49
问题 Suppose I have an XML string: <A> <B foo="123"> <C>thing</C> <D>stuff</D> </B> </A> and I want to insert a namespace of the type used by XML Schema, putting a prefix in front of all the element names. <A xmlns:ns1="www.example.com"> <ns1:B foo="123"> <ns1:C>thing</ns1:C> <ns1:D>stuff</ns1:D> </ns1:B> </A> Is there a way to do this (aside from brute-force find-replace or regex) using lxml.etree or a similar library? 回答1: I don't think this can be done with just ElementTree. Manipulating