把多个xmL文件数据整合到另一个文件xml中

把多个xmL文件内容写入到另一个文件xml中

"""
把多个xmL文件写入到一个文件xml中
"""
import os
import xml.etree.ElementTree as ET


# 加空格解决排版问题
def indent(elem, level=0):
    i = "\n" + level * " "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + " "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i


def handle_xml(image_name, src_path):
    # 判断是否有根节点
    try:
        tree = ET.parse("pre_knowledge.xml")
        root = tree.getroot()  # 数据内存地址
        # print(root.tag)  # 标签
    except:
        # 创建根节点
        root = ET.Element("root")
        # print(root)

    annotation = ET.SubElement(root, "annotation")
    deviceid = ET.SubElement(annotation, "deviceid")  # SubElement 子节点
    list01 = image_name.split("_")
    name_text = list01[1] + '_' + list01[2]
    deviceid.text = name_text
    # 写入元素节点
    # 读取文件,然后依次遍历每个文件下xml的size标签属性和object标签属性
    # print(os.path.join(src_path,image_name))
    target_dom = ET.parse(os.path.join(src_path, image_name))
    target_root = target_dom.getroot()  # 数据内存地址
    # print(target_dom)
    # 创建子节点
    size = ET.SubElement(deviceid, "size")  # SubElement 子节点
    for ta in target_root.iter("size"):
        for i in ta:
            i_tag = ET.SubElement(size, i.tag)  # SubElement 子节点
            i_tag.text = i.text

    for i in target_root.iter('object'):
        object = ET.SubElement(deviceid, "object")
        for j in i:
            if j.tag == 'name':
                j_tag = ET.SubElement(object, j.tag)  # SubElement 子节点
                j_tag.text = j.text
                print(j.tag, j.text)
            if j.tag == 'bndbox':
                j_tag = ET.SubElement(object, j.tag)  # SubElement 子节点
                for m in j:
                    m_tag = ET.SubElement(j_tag, m.tag)  # SubElement 子节点
                    m_tag.text = m.text

    # 保存
    indent(root)
    et = ET.ElementTree(root)  # 生成文档对象
    et.write("pre_knowledge01.xml", encoding="utf-8", xml_declaration=True)
    # 显示结果
    # ET.dump(root)


if __name__ == "__main__":
    src_path = 'D:/picture/error_fencuo/xml/'
    f = open('pre_knowledge.xml', 'a', encoding='utf-8')
    for path, dirs, files in os.walk(src_path):
        for file_name in files:
            print(file_name)
            if not file_name.endswith('.xml'):
                continue
            handle_xml(file_name, src_path)
    f.close()
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
非常感谢您的问题!以下是您所需要的代码: 首先,在您的Spring Boot项目,您需要在pom.xml文件添加以下依赖项: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> ``` 接下来,您需要在application.properties文件配置您的数据源信息,例如: ```properties # 主数据源配置 spring.datasource.primary.url=jdbc:mysql://localhost:3306/primary_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.primary.username=root spring.datasource.primary.password=root spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver # 第二个数据源配置 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.secondary.username=root spring.datasource.secondary.password=root spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver ``` 然后,您需要创建两个数据源的配置类,例如: ```java @Configuration @MapperScan(basePackages = "com.example.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class PrimaryDataSourceConfig { @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "primarySqlSessionFactory") public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "primaryTransactionManager") public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "primarySqlSessionTemplate") public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` ```java @Configuration @MapperScan(basePackages = "com.example.mapper.secondary", sqlSessionTemplateRef = "secondarySqlSessionTemplate") public class SecondaryDataSourceConfig { @Bean(name = "secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondarySqlSessionFactory") public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "secondaryTransactionManager") public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "secondarySqlSessionTemplate") public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 接下来,您需要创建Mapper接口和对应的XML文件,例如: ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user") List<User> getAllUsers(); } ``` ```xml <mapper namespace="com.example.mapper.primary.UserMapper"> <resultMap id="userMap" type="com.example.entity.User"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> </resultMap> <select id="getAllUsers" resultMap="userMap"> SELECT * FROM user </select> </mapper> ``` 最后,您可以在您的代码使用Mapper接口来查询数据,例如: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> getAllUsers() { return userMapper.getAllUsers(); } } ``` 希望这个代码能够帮助您!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值