beautifulsoup - 如何使用 BeautifulSoup 创建带有孩子的 xml 树
问题描述
这是目标
<?xml version="1.0"?>
<opencv_storage>
<intr type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>d</dt>
<data>
1.4575724387217269e+03 0. 1.2129456942116219e+03 0.
1.4575222265029629e+03 1.0073205884892100e+03 0. 0. 1.</data></intr>
</opencv_storage>
这是我的尝试
from bs4 import BeautifulSoup
soup = BeautifulSoup(features = "xml")
parent = soup.new_tag("opencv_storage")
soup.append(parent)
t = soup.parent
child_row = soup.new_tag("rows")
child_row.string = str(3)
soup.parent.insert_child(child_row)
产生错误
Traceback (most recent call last):
File "/home/test.py", line 22, in <module>
soup.parent.insert_child(child_row)
AttributeError: 'NoneType' object has no attribute 'insert_child'
除了告诉我如何纠正这个错误,请提供命令参考
解决方案
这似乎有效
from bs4 import BeautifulSoup
import numpy as np
html = '<opencv_storage><intr type_id="opencv-matrix"></opencv_storage>'
soup = BeautifulSoup(html, features = "xml")
child_row = soup.new_tag("rows")
child_row.string="3"
soup.intr.insert_after(child_row)
child_col = soup.new_tag("cols")
child_col.string="3"
soup.rows.insert_after(child_col)
child_dt = soup.new_tag("dt")
child_dt.string="d"
soup.cols.insert_after(child_dt)
arr = np.array([[1.4575724387217269e+03, 0., 1.2129456942116219e+03],
[0., 1.4575222265029629e+03, 1.0073205884892100e+03],
[0., 0., 1]])
child_data = soup.new_tag("data")
child_data.string=str(arr.flatten()).strip("[]")
soup.dt.insert_after(child_data)
print(soup.prettify())
输出
<?xml version="1.0" encoding="utf-8"?>
<opencv_storage>
<intr type_id="opencv-matrix"/>
<rows>
3
</rows>
<cols>
3
</cols>
<dt>
d
</dt>
<data>
1.45757244e+03 0.00000000e+00 1.21294569e+03 0.00000000e+00
1.45752223e+03 1.00732059e+03 0.00000000e+00 0.00000000e+00
1.00000000e+00
</data>
</opencv_storage>
推荐阅读
- sql-server - 从另一列中减去一列并获得运行总 SQL Server 2008 R2
- .net - VBA - ActiveX 无法为具有依赖关系的 .net dll 创建对象
- css - 从访问数据库中按年份获取不同的计数
- javascript - 为什么记录 fetch() 的结果会“破坏”它(“主体流被锁定”)?
- dart - How to change background color of ListTile?
- c# - 如何从我的项目访问我的 MongoDB 实例到我的 xunit 测试项目类?
- android - 我怎样才能将我的图像放在一个圆圈中而不出现在 Android Studio 上?
- python - 创建“压缩”字典
- php - 使用命名空间(PHP)从另一个类调用方法
- java - 在其他语言中状态为 200 时,在 Java 中登录后重定向 302