1#!/usr/bin/env python3 2 3# CDDL HEADER START 4# 5# The contents of this file are subject to the terms of the 6# Common Development and Distribution License (the "License"). 7# You may not use this file except in compliance with the License. 8# 9# See LICENSE.txt included in this distribution for the specific 10# language governing permissions and limitations under the License. 11# 12# When distributing Covered Code, include this CDDL HEADER in each 13# file and include the License file at LICENSE.txt. 14# If applicable, add the following below this CDDL HEADER, with the 15# fields enclosed by brackets "[]" replaced with your own identifying 16# information: Portions Copyright [yyyy] [name of copyright owner] 17# 18# CDDL HEADER END 19 20# 21# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. 22# 23 24import xml.etree.ElementTree as ET 25 26 27class XMLProcessingException(Exception): 28 pass 29 30 31def insert_file(input_xml, insert_xml_file): 32 """ 33 inserts sub-root elements of XML file under root of input XML 34 :param input_xml: input XML string 35 :param insert_xml_file: path to file to insert 36 :return: string with resulting XML 37 """ 38 39 # This avoids resulting XML to have namespace prefixes in elements. 40 ET.register_namespace('', "https://jakarta.ee/xml/ns/jakartaee") 41 42 root = ET.fromstring(input_xml) 43 try: 44 insert_tree = ET.parse(insert_xml_file) 45 except ET.ParseError as e: 46 raise XMLProcessingException("Cannot parse file '{}' as XML". 47 format(insert_xml_file)) from e 48 except (PermissionError, IOError) as e: 49 raise XMLProcessingException("Cannot read file '{}'". 50 format(insert_xml_file)) from e 51 52 insert_root = insert_tree.getroot() 53 54 for elem in list(insert_root.findall('.')): 55 root.extend(list(elem)) 56 57 return ET.tostring(root, encoding="utf8", method='xml').decode("utf-8") 58