python - Move an entire element in with lxml.etree -
python - Move an entire element in with lxml.etree -
within lxml, possible, given element, move entire thing elsewhere in xml document without having read of it's children , recreate it? best illustration changing parents. i've rummaged around docs bit haven't had much luck. in advance!
.append
, .insert
, other operations default
>>> lxml import etree >>> tree = etree.xml('<a><b><c/></b><d><e><f/></e></d></a>') >>> node_b = tree.xpath('/a/b')[0] >>> node_d = tree.xpath('/a/d')[0] >>> node_d.append(node_b) >>> etree.tostring(tree) # finish 'b'-branch under 'd', after 'e' '<a><d><e><f/></e><b><c/></b></d></a>' >>> node_f = tree.xpath('/a/d/e/f')[0] # nil stops moving 1 time again >>> node_f.append(node_a) # 'a' deep under 'f' >>> etree.tostring(tree) '<a><d><e><f><b><c/></b></f></e></d></a>'
be careful when moving nodes having tail text. in lxml tail text belong node , moves around it. (also, when delete node, tail text deleted)
>>> tree = etree.xml('<a><b><c/></b>tail<d><e><f/></e></d></a>') >>> node_b = tree.xpath('/a/b')[0] >>> node_d = tree.xpath('/a/d')[0] >>> node_d.append(node_b) >>> etree.tostring(tree) '<a><d><e><f/></e><b><c/></b>tail</d></a>'
sometimes it's desired effect, need that:
>>> tree = etree.xml('<a><b><c/></b>tail<d><e><f/></e></d></a>') >>> node_b = tree.xpath('/a/b')[0] >>> node_d = tree.xpath('/a/d')[0] >>> node_a = tree.xpath('/a')[0] >>> # manually move text >>> node_a.text = node_b.tail >>> node_b.tail = none >>> node_d.append(node_b) >>> etree.tostring(tree) >>> # tail text stays within old place '<a>tail<d><e><f/></e><b><c/></b></d></a>'
python xml lxml
Comments
Post a Comment