【Python基础】lxml操作xml文件

1. 内存中创建xml格式数据

from lxml import etree as ET
node_root = ET.Element('root')  # 创建根节点
node_root.set('attribte', 'root-title') # 设置根节点属性attribte = root-title
node_root_span = ET.SubElement(node_root, 'span')  # 根节点下新增子节点span
node_root_span.set('attribte', 'ttttttttt') # 子节点span新增属性attribte = tttttt
# =======================建议使用以下方法新增子节点==================================#
node_root_span_s1 = ET.SubElement(node_root_span, 's1')  # 子节点span新增子节点s1
# ================================================================================#
node_root_span_s3 = ET.SubElement(node_root_span, 's3')
node_root.insert(0, ET.Element('First')) #[无返回对象] 根节点第一位置插入First子节点
node_root_span.insert(1, ET.Element('s2')) #[无返回对象] 新增子节点s2
node_root_span_s1.set('df', '2345') # 设置s1节点属性
node_root.append(ET.Element('Last')) #[无返回对象]  在根节点末尾新增Last节点
print(ET.tostring(node_root, pretty_print=True).decode('utf-8'))

打印结果如下:

<root attribte="root-title">
  <First/>
  <span attribte="ttttttttt">
    <s1 df="2345"/>
    <s2/>
    <s3/>
  </span>
  <Last/>
</root>

2. 定位/操作xml文件

给定以下xml文件:

<?xml version='1.0' encoding='UTF-8'?>
<xmltest>
  <lag>
    <python class="item1">
      <a href="link1.html">Python</a>
    </python>
    <Java class="item2">
      <a href="link2.html">Java</a>
    </Java>
    <C class="site1">
      <a href="c.biancheng.net">C语言中文网</a>
    </C>
  </lag>
  <url>
    <BaiDu class="site2">
      <Net Adr="www.baidu.com"/>
      <Loc Num="0">Beijing</Loc>
      <CEO>LI</CEO>
    </BaiDu>
    <JingDong class="site3">
      <Net Adr="www.jd.com"/>
      <Loc Num="0">Beijing</Loc>
      <CEO>LIU</CEO>
    </JingDong>
  </url>
  <bookstore>
    <book>
      <title lang="en">Harry Potter</title>
      <author>J.K. Rowling</author>
      <price>29.99</price>
    </book>
    <book>
      <title lang="en">Learning XML</title>
      <author>Erik T. Ray</author>
      <price>39.95</price>
    </book>
    <book>
      <title lang="zh-CN">西游记</title>
      <author>吴承恩</author>
      <price>28.80</price>
    </book>
  </bookstore>
</xmltest>

2.1 载入xml并获取根节点

from lxml import etree as ET
parser = ET.XMLParser(remove_blank_text=True)  # 去除空白行
test_xml = ET.parse('test.xml', parser)  # 加载xml文件
node_root =  test_xml.getroot() # 获取根节点: xmltest

2.2 获取子节点属性和文本

lag_node = root_node.xpath('lag')[0] # 定位到根节点下lag子节点 [index]索引必须
attrib_text = lag_node.xpath('./python/a')[0].attrib['href'] #当前节点下python-a的属性
print(attrib_text) # link1.html
lag_C_text = lag_node.xpath('./C/a')[0].text #当前节点下C-a的文本
print(lag_C_text) # C语言中文网

2.3 修改子节点属性和文本

# 修改节点属性值
baidu_node = root_node.xpath('url/BaiDu')[0] # 定位BaiDu子节点
baidu_node.attrib['class'] = 'Get2' # 将BaiDu子节点属性修改为Get2(修改后需要保存)
...
    <BaiDu class="Get2">
      <Net Adr="www.baidu.com"/>
      <Loc Num="0">Beijing</Loc>
      <CEO>LI</CEO>
    </BaiDu>
# 修改节点文本值
books = root_node.xpath('bookstore')[0] # 定位子节点
books.xpath('./book/title[@lang=\'zh-CN\']')[0].text = '水许传'
# 通过@定位特定属性值:book/title@属性lang=zh-CN的节点text修改为水许传
# \'的意思是转义字符(较为常用)
...
    <book>
      <title lang="zh-CN">水许传</title>
      <author>吴承恩</author>
      <price>28.80</price>
    </book>
# xpath定位节点信息
# book/title@属性lang=en的第二个节点text
book_name = books.xpath('./book/title[@lang=\'en\']')[1].text
print(book_name) # Learning XML

@属性的方法也可以配合‘{}’.format()格式化进行定位使用,【例如】

# 上文提到的文本替换同样可以通过以下方法执行
books = root_node.xpath('bookstore')[0] # 定位子节点
books.xpath('./book/title[@lang=\'{}\']'.format('zh-CN'))[0].text = '西游记'
...
    <book>
      <title lang="zh-CN">西游记</title>
      <author>吴承恩</author>
      <price>28.80</price>
    </book>

2.4 保存更改

test_xml.write('test.xml', encoding='utf-8', xml_declaration=True, pretty_print=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值