Я пытаюсь обновить XML-файл ниже в python 3, используя импорт xml.etree.ElementTree как ET, но не могу ничего добавить между тегами
Проблема, с которой я столкнулся, не может получить/извлечь тег после файловых наборов. Может ли кто-нибудь сообщить мне, как мы можем обновить xml?
abc.xml
<assembly
xmlns = "http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
http://maven.apache.org/xsd/assembly-1.1.2-xsd"
>
<id></id>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<outputDirectory>/<outputDirectory>
<directory>../</directory>
<useDefaultExcludes>false</useDefaultExcludes>
<includes>
</includes>
</fileSet>
</fileSets>
</assembly>
Ожидаемый результат: (имена файлов будут добавляться динамически) abc.xml
<assembly
xmlns = "http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
http://maven.apache.org/xsd/assembly-1.1.2-xsd"
>
<id></id>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<outputDirectory>/<outputDirectory>
<directory>../</directory>
<useDefaultExcludes>false</useDefaultExcludes>
<includes>
<include>abc.text</include>
<include>def.text</include>
<include>ghi.text</include>
</includes>
</fileSet>
</fileSets>
</assembly>
Я пытаюсь это сделать, и он печатает все четыре элемента внутри этих файлов, но не знает, как получить доступ к ним, а затем добавить что-то в этот abc.txt и так далее.
import xml.etree.ElementTree as ET
tree = ET.parse(abc.xml)
root = tree.getroot()
for actor in root.findall('{http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2}fileSets'):
for name in actor.findall('{http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2}fileSet'):
print(name)
@mzjn yes Вы можете увидеть ожидаемый результат
abc.xml имеет пространство имен по умолчанию, которое необходимо учитывать. docs.python.org/3/library/…
@mzjn обновил код, но все еще не знает, как добраться до определенного элемента и добавить (упомянутый выше)
Вам не нужно ничего делать с fileSets
или fileSet
. Поскольку вы хотите добавить детей к includes
, получите этот элемент напрямую.
import xml.etree.ElementTree as ET
# Ensure that the proper prefix is used in the output (in this case, no prefix at all)
ET.register_namespace("", "http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2")
tree = ET.parse("abc.xml")
# Find the 'includes' element (.// means search the whole document).
# {*} is a wildcard and matches any namespace (Python 3.8)
includes = tree.find(".//{*}includes")
# Create three new 'include' elements
include1 = ET.Element("include")
include1.text = "abc.text"
include2 = ET.Element("include")
include2.text = "def.text"
include3 = ET.Element("include")
include3.text = "ghi.text"
# Add the new elements as children of 'includes'
includes.append(include1)
includes.append(include2)
includes.append(include3)
Итак, вы хотите добавить три элемента
include
в качестве дочерних элементовincludes
?