【Python】从SAP2000 XML截面库提取数据到Excel

从SAP2000 XML截面库提取数据到Excel

问题

SAP2000的截面库是XML格式,带有命名空间,直接用Python解析会找不到元素。

解决方案

python 复制代码
import xml.etree.ElementTree as ET
import pandas as pd

# XML文件路径
path = r'E:\Program Files\Computers and Structures\SAP2000 26\Property Libraries\Sections\BSShapes2006.xml'

tree = ET.parse(path)
root = tree.getroot()

# 关键:定义命名空间
ns = {'csi': 'http://www.csiberkeley.com'}

# 提取数据(以STEEL_ANGLE为例,可改成其他截面类型)
data = []
for section in root.findall('.//csi:STEEL_ANGLE', ns):
    row = {}
    for child in section:
        tag = child.tag.replace('{http://www.csiberkeley.com}', '')
        row[tag] = child.text
    data.append(row)

# 导出Excel
df = pd.DataFrame(data)
df.to_excel('sections.xlsx', index=False)

常见截面类型标签

标签 截面类型
STEEL_ANGLE 角钢
STEEL_I_SECTION 工字钢
STEEL_CHANNEL 槽钢
STEEL_TEE T型钢
STEEL_TUBE 方管
STEEL_PIPE 圆管

批量提取所有类型

python 复制代码
import xml.etree.ElementTree as ET
import pandas as pd

path = r'你的XML路径.xml'
tree = ET.parse(path)
root = tree.getroot()

ns = {'csi': 'http://www.csiberkeley.com'}
section_types = ['STEEL_ANGLE', 'STEEL_I_SECTION', 'STEEL_CHANNEL', 
                 'STEEL_TEE', 'STEEL_TUBE', 'STEEL_PIPE']

with pd.ExcelWriter('all_sections.xlsx') as writer:
    for sec_type in section_types:
        data = []
        for section in root.findall(f'.//csi:{sec_type}', ns):
            row = {child.tag.split('}')[1]: child.text for child in section}
            data.append(row)
        if data:
            pd.DataFrame(data).to_excel(writer, sheet_name=sec_type, index=False)

依赖

bash 复制代码
pip install pandas openpyxl
相关推荐
小猴子爱上树9 分钟前
Temu批量视频翻译Python实现方案
开发语言·python·音视频
X1A0RAN23 分钟前
Python 并发请求性能优化实战
python·性能优化·并发编程
陈同学xxx28 分钟前
Hermes Agent 接入飞书,在手机上随时聊天
linux·python·飞书
卷无止境33 分钟前
Python 中基于 Qt 的 GUI 库授权方式全解析
后端·python
卷无止境1 小时前
Guardrails.ai:为大语言模型加一道"安全阀"
后端·python
汤姆小白5 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
向日的葵00611 小时前
langchain的Tools教程(三)
python·langchain·tools
言乐613 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
YUS云生13 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
智写-AI13 小时前
真实有效的免费降英文AI工具服务商
人工智能·python