簡體   English   中英

即使當pretty_print = True時,使用lxml編寫也不會產生空格

[英]Writing with lxml emitting no whitespace even when pretty_print=True

我正在使用lxml庫讀取xml模板,插入/更改一些元素,然后保存生成的xml。 我正在使用etree.Elementetree.SubElement方法etree.Element創建的元素之一:

tree = etree.parse(r'xml_archive\templates\metadata_template_pts.xml')
root = tree.getroot()

stream = []
for element in root.iter():
    if isinstance(element.tag, basestring):
        stream.append(element.tag)

        # Find "keywords" element and insert a new "theme" element
        if element.tag == 'keywords' and 'theme' not in stream:
            theme = etree.Element('theme')
            themekt = etree.SubElement(theme, 'themekt').text = 'None'
            for tk in themekeys:
                themekey = etree.SubElement(theme, 'themekey').text = tk
            element.insert(0, theme)

打印到屏幕上很好地print etree.tostring(theme, pretty_print=True)

<theme>
  <themekt>None</themekt>
  <themekey>Hydrogeology</themekey>
  <themekey>Stratigraphy</themekey>
  <themekey>Floridan aquifer system</themekey>
  <themekey>Geology</themekey>
  <themekey>Regional Groundwater Availability Study</themekey>
  <themekey>USGS</themekey>
  <themekey>United States Geological Survey</themekey>
  <themekey>thickness</themekey>
  <themekey>altitude</themekey>
  <themekey>extent</themekey>
  <themekey>regions</themekey>
  <themekey>upper confining unit</themekey>
  <themekey>FAS</themekey>
  <themekey>base</themekey>
  <themekey>geologic units</themekey>
  <themekey>geology</themekey>
  <themekey>extent</themekey>
  <themekey>inlandWaters</themekey>
</theme>

但是,當使用etree.ElementTree(root).write(out_xml_file, method='xml', pretty_print=True)寫出xml時,此元素在輸出文件中變平:

<theme><themekt>None</themekt><themekey>Hydrogeology</themekey><themekey>Stratigraphy</themekey><themekey>Floridan aquifer system</themekey><themekey>Geology</themekey><themekey>Regional Groundwater Availability Study</themekey><themekey>USGS</themekey><themekey>United States Geological Survey</themekey><themekey>thickness</themekey><themekey>altitude</themekey><themekey>extent</themekey><themekey>regions</themekey><themekey>upper confining unit</themekey><themekey>FAS</themekey><themekey>base</themekey><themekey>geologic units</themekey><themekey>geology</themekey><themekey>extent</themekey><themekey>inlandWaters</themekey></theme>

文件的其余部分寫得很好,但是此特定元素引起了(純粹是美觀的)麻煩。 關於我在做什么錯的任何想法?


以下是模板xml文件中的標記片段(將其另存為“ template.xml”,以便在底部使用代碼片段運行)。 僅當我解析現有文件並插入新元素時才進行標簽的拼合,而不是使用lxml從頭開始創建xml時才進行。

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="fgdc_classic.xsl"?>
<metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://water.usgs.gov/GIS/metadata/usgswrd/fgdc-std-001-1998.xsd">
    <keywords>
       <theme>
            <themekt>ISO 19115 Topic Categories</themekt>
            <themekey>environment</themekey>
            <themekey>geoscientificInformation</themekey>
            <themekey>inlandWaters</themekey>
        </theme>
        <place>
            <placekt>None</placekt>
            <placekey>Florida</placekey>
            <placekey>Georgia</placekey>
            <placekey>Alabama</placekey>
            <placekey>South Carolina</placekey>
        </place>
    </keywords>

</metadata>

以下是要與標記代碼段一起使用的代碼段(以上):

# Create new theme element to insert into root
themekeys = ['Hydrogeology', 'Stratigraphy', 'inlandWaters']

tree = etree.parse(r'template.xml')
root = tree.getroot()

stream = []
for element in root.iter():
    if isinstance(element.tag, basestring):
        stream.append(element.tag)

        # Edit theme keywords
        if element.tag == 'keywords':
            theme = etree.Element('theme')
            themekt = etree.SubElement(theme, 'themekt').text = 'None'
            for tk in themekeys:
                themekey = etree.SubElement(theme, 'themekey').text = tk
            element.insert(0, theme)

# Write XML to new file
out_xml_file = 'test.xml'
etree.ElementTree(root).write(out_xml_file, method='xml', pretty_print=True)
with open(out_xml_file, 'r') as f:
    lines = f.readlines()

with open(out_xml_file, 'w') as f:
    f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    for line in lines:
        f.write(line)

如果替換此行:

tree = etree.parse(r'template.xml')

這些行:

parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(r'template.xml', parser)

然后它將按預期工作。 訣竅是使用XMLParser ,該XMLParserremove_blank_text選項設置為True 任何現有的可忽略空白都將被刪除,因此不會中斷后續的漂亮打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM