在将新元素插入现有xml中时,lxml不添加换行符 [英] lxml not adding newlines when inserting a new element into existing xml

查看:103
本文介绍了在将新元素插入现有xml中时,lxml不添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大套现有的xml文件,并且我试图向其中的所有文件添加一个元素(它们是pom.xml用于许多Maven项目,并且我试图向其所有元素添加一个父元素.他们).以下是我的确切代码.

I have a large set of existing xml files, and I am trying to add one element to all of them (they are pom.xml for a number of maven projects, and I am trying to add a parent element to all of them). The following is my exact code.

问题是pom2.xml中的最终xml输出在一行中具有完整的parent元素.不过,当我单独打印元素时,它会像往常一样将其写成4行.如何为parent元素以正确的格式打印出完整的xml?

The problem is that the final xml output in pom2.xml has the complete parent element in a single line. Though, when I print the element by itself, it writes it out in 4 lines as usual. How do I print out the complete xml with proper formatting for the parent element?

from lxml import etree

parentPom = etree.Element('parent')
groupId = etree.Element('groupId')
groupId.text = 'org.myorg'
parentPom.append(groupId)

artifactId = etree.Element('artifactId')
artifactId.text = 'myorg-master-pom'
parentPom.append(artifactId)

version = etree.Element('version')
version.text = '1.0.0'
parentPom.append(version)

print etree.tostring(parentPom, pretty_print=True)

pom = etree.parse("pom.xml")
projectElement = pom.getroot()
projectElement.insert(0, parentPom)

file = open("pom2.xml", 'wb')
file.write(etree.tostring(projectElement, pretty_print=True))
file.close()

打印输出:

<parent>
  <groupId>org.myorg</groupId>
  <artifactId>myorg-master-pom</artifactId>
  <version>1.0.0</version>
</parent>

pom2.xml中相同元素的输出:

Output of same element in pom2.xml:

<parent><groupId>com.inmobi</groupId><artifactId>inmobi-master-pom</artifactId><version>1.0.1</version></parent><modelVersion>4.0.0</modelVersion>

推荐答案

这可能对您来说很有趣.

This might be of intrest to you.

http: //lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output

简而言之,供以后参考:

In short for future reference:

parser = etree.XMLParser(remove_blank_text=True)
pom = etree.parse("pom.xml",parser)

这篇关于在将新元素插入现有xml中时,lxml不添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆