python将字符串写入xml中,python如何将空树节点作为空字符串写入xmlfi

import lxml.etree as et

xml = et.parse("test.xml")

for node in xml.xpath("//neighbor"):

node.getparent().remove(node)

xml.write("out.xml",encoding="utf-8",xml_declaration=True)

使用elementTree,我们需要找到parents of the neighbor nodes,然后找到neighbor nodes inside that parent并删除它们:

^{pr2}$

两者都会给你:<?xml version='1.0' encoding='utf-8'?>

1

2008

141100

4

2011

59900

68

2011

13600

使用属性逻辑并修改xml,如下所示:x = """<?xml version="1.0"?>

1

2008

141100

4

2011

59900

68

2011

13600

"""

使用lxml:import lxml.etree as et

xml = et.fromstring(x)

for node in xml.xpath("//neighbor[not(@make) and not(@job) and not(@make)]"):

node.getparent().remove(node)

print(et.tostring(xml))

会给你:

1

2008

141100

4

2011

59900

68

2011

13600

ElementTree中的相同逻辑:from xml.etree import ElementTree as et

xml = et.parse("test.xml").getroot()

atts = {"build", "job", "make"}

for parent in xml.findall(".//neighbor/.."):

for child in parent.findall(".//neighbor")[:]:

if not atts.issubset(child.attrib):

parent.remove(child)

如果您正在使用iter:from xml.etree import ElementTree as et

xml = et.parse("test.xml")

for parent in xml.getroot().iter("*"):

parent[:] = (child for child in parent if child.tag != "neighbor")

你可以看到我们得到完全相同的输出:In [30]: !cat /home/padraic/untitled6/test.xml

#

1

2008

141100

4

2011

59900

68

2011

13600

In [31]: paste

def test():

import lxml.etree as et

xml = et.parse("/home/padraic/untitled6/test.xml")

for node in xml.xpath("//neighbor"):

node.getparent().remove(node)

a = et.tostring(xml)

from xml.etree import ElementTree as et

xml = et.parse("/home/padraic/untitled6/test.xml")

for parent in xml.getroot().iter("*"):

parent[:] = (child for child in parent if child.tag != "neighbor")

b = et.tostring(xml.getroot())

assert a == b

## End pasted text

In [32]: test()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值