Tôi có một tài liệu trong đó sử dụng một không gian tên XML mà tôi muốn tăng /group/house/dogs
bởi một: (các tập tin được gọi là houses.xml
)Python: Cập nhật file XML sử dụng ElementTree trong khi bảo tồn bố trí càng nhiều càng tốt
<?xml version="1.0"?>
<group xmlns="http://dogs.house.local">
<house>
<id>2821</id>
<dogs>2</dogs>
</house>
</group>
kết quả hiện tại của tôi bằng cách sử dụng mã dưới đây là: (các tập tin được tạo ra được gọi là houses2.xml
)
<ns0:group xmlns:ns0="http://dogs.house.local">
<ns0:house>
<ns0:id>2821</ns0:id>
<ns0:dogs>3</ns0:dogs>
</ns0:house>
</ns0:group>
tôi muốn sửa chữa hai điều (nếu nó có thể sử dụng ElementTree Nếu nó không được, tôi muốn được. tuyệt vời cho một gợi ý về những gì tôi nên sử dụng thay vào đó) :
- Tôi muốn giữ dòng
<?xml version="1.0"?>
. - Tôi không muốn thêm tiền tố vào tất cả các thẻ, tôi muốn giữ nguyên nó.
Kết luận, Tôi không muốn gây rối với tài liệu nhiều hơn tôi hoàn toàn phải làm.
Mã hiện tại của tôi (hoạt động ngoại trừ các lỗ hổng được đề cập ở trên) tạo ra kết quả ở trên theo sau.
Tôi đã thực hiện một chức năng tiện ích mà tải một file XML sử dụng ElementTree và trả về ElementTree và không gian tên (như tôi không muốn cứng mã namespace, và sẵn sàng chấp nhận rủi ro nó ngụ ý):
def elementTreeRootAndNamespace(xml_file):
from xml.etree import ElementTree
import re
element_tree = ElementTree.parse(xml_file)
# Search for a namespace on the root tag
namespace_search = re.search('^({\S+})', element_tree.getroot().tag)
# Keep the namespace empty if none exists, if a namespace exists set
# namespace to {namespacename}
namespace = ''
if namespace_search:
namespace = namespace_search.group(1)
return element_tree, namespace
Đây là mã của tôi để cập nhật số lượng chó và lưu nó vào tập tin mới houses2.xml
:
elementTree, namespace = elementTreeRootAndNamespace('houses.xml')
# Insert the namespace before each tag when when finding current number of dogs,
# as ElementTree requires the namespace to be prefixed within {...} when a
# namespace is used in the document.
dogs = elementTree.find('{ns}house/{ns}dogs'.format(ns = namespace))
# Increase the number of dogs by one
dogs.text = str(int(dogs.text) + 1)
# Write the result to the new file houses2.xml.
elementTree.write('houses2.xml')
Tôi đoán đây là bản sao của http://stackoverflow.com/questions/8983041/saving-xml-files-using-elementtree và http://stackoverflow.com/questions/18338807/cannot-write-xml- không gian tên tập tin với mặc định – leo