목록에서 일부 노드와 값을 추가하여 일부 XML을 변경하고 있습니다. 모든 새로운 태그와 값을 성공적으로 만들 수 있습니다. contributors 태그 사이에 태그를 만들고 있지만 xml을 새 파일에 저장하면 내가 만드는 태그가 모두 한 줄에 표시됩니다.python xml pretty print not working
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True) # makes pretty print work
path3 = 'path_to_xml_file'
open(path3)
tree = etree.parse(path3, parser)
root = tree.getroot()
tree.write(xmlFileOut, pretty_print = True, xml_declaration = True, encoding = 'UTF-8')
: 아래의 코드를 사용하여 작업 할 XML 파일을 열 때 나는이 문제를 해결 한
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<package>
<delivery_type>new</delivery_type>
<feature>
<feature_type>Movie</feature_type>
<contributors>
<contributor type="cast"><name>John Doe</name><role>actor</role></contributor><contributor type="cast"><name>Another Actors name</name><role>actor</role></contributor><contributor type="cast"><name>Jane Doe</name><role>actor</role></contributor><contributor type="cast"><name>John Smith</name><role>actor</role></contributor></contributors>
</package>
:
여기templateXml = """<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<package>
<delivery_type>new</delivery_type>
<feature>
<feature_type>Movie</feature_type>
<contributors>
</contributors>
</package>"""
from lxml import etree
tree = etree.fromstring(templateXml)
node_video = tree.xpath('//feature/contributors')[0]
for cast in castList:
pageElement = etree.SubElement(node_video, 'contributor')
node_video1 = tree.xpath('//feature/contributors/contributor')[0]
pageElement.attrib['type'] = 'cast'
pageElement1 = etree.SubElement(pageElement, 'name')
pageElement1.text = cast.text
pageElement2 = etree.SubElement(pageElement, 'role')
pageElement2.text = "actor"
xmlFileOut = '/Users/User1/Desktop/Python/Done.xml'
with open(xmlFileOut, "w") as f:
f.write(etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes"))
는 XML 파일에 저장됩니다 : 여기 내 코드의 샘플입니다
이 방법이 유용하지만 어떻게 문자열 xml과 함께 사용할 수 있습니까?