5

リストからいくつかのノードと値を追加して、いくつかのxmlを変更しています。すべての新しいタグと値を正常に作成できます。contributors タグの間に作成していますが、xml を新しいファイルに保存すると、作成したタグはすべて 1 行になります。これが私のコードのサンプルです:

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 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>

以下のコードを使用して作業するためにxmlファイルを開くときに、この問題を解決しました。

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 で機能させるにはどうすればよいですか?

4

2 に答える 2

3

http://ruslanspivak.com/2014/05/12/how-to-pretty-print-xml-with-lxml/から取得

import StringIO
import lxml.etree as etree

def prettify(xml_text):
    """Pretty prints xml."""
    parser = etree.XMLParser(remove_blank_text=True)
    file_obj = StringIO.StringIO(xml_text)
    tree = etree.parse(file_obj, parser)
    return etree.tostring(tree, pretty_print=True)
于 2015-02-06T06:37:21.970 に答える