[英]How to remove Root tag and keep rest all row tags in an xml using python
[英]How to keep sequence of XML tags even add/remove a tag using python
我正在 python 中尋找以下解決方案。 以下是我目前的 xml 文件格式。
<step_1>abc</step_1>
<step_2>efg</step_2>
<step_3>hij</step_3>
<step_4>klm</step_4>
我想在第一個和最后一個之間添加/刪除一個標簽,並按順序維護標簽的命名。 例如:如果我刪除<step_2>efg</step_2>
那么結果應該如下
<step_1>abc</step_1>
<step_2>hij</step_2>
<step_3>klm</step_3>
有什么解決辦法嗎? 先感謝您。
我檢查了 XML 元素的標記屬性可以修改,至少使用lxml 。
我的解決方案基於lxml的另一個原因是它包含xpath方法,這是此處需要的。
首先,假設您在源代碼樹中添加或刪除了一些step_...元素,還有其他名稱的元素,現在整個樹包含:
<main>
<xx>
<other>a1</other>
<step_1>abc</step_1>
<step_3>hij</step_3>
<other>a2</other>
<step_4>klm</step_4>
<step_6>xyz</step_6>
</xx>
<yy>
<step_1>abc_2</step_1>
<step_7>xyz_2</step_7>
<step_2>efg_2</step_2>
<other>a3</other>
<step_4>klm_2</step_4>
</yy>
</main>
我從一個文件中讀取了上述內容:
from lxml import etree as et
parser = et.XMLParser(remove_blank_text=True)
tree = et.parse('Input.xml', parser)
root = tree.getroot()
那么這個想法是:
帶有測試打印輸出的代碼是:
for el in root.xpath(".//*[starts-with(name(), 'step')]/.."):
tg = el.tag
print(f'Parent: {tg:7}')
i = 0
for el2 in el.xpath("*[starts-with(name(), 'step')]"):
i += 1
tg2 = el2.tag
tt = el2.text
if tt is None: tt = ''
newName = f'step_{i}'
print(f' Child {i}: {tg2:7} {tt:8} -> {newName}')
el2.tag = newName
它打印:
Parent: xx
Child 1: step_1 abc -> step_1
Child 2: step_3 hij -> step_2
Child 3: step_4 klm -> step_3
Child 4: step_6 xyz -> step_4
Parent: yy
Child 1: step_1 abc_2 -> step_1
Child 2: step_7 xyz_2 -> step_2
Child 3: step_2 efg_2 -> step_3
Child 4: step_4 klm_2 -> step_4
現在打印內容時:
print(et.tostring(root, encoding='unicode', pretty_print=True))
結果是:
<main>
<xx>
<other>a1</other>
<step_1>abc</step_1>
<step_2>hij</step_2>
<other>a2</other>
<step_3>klm</step_3>
<step_4>xyz</step_4>
</xx>
<yy>
<step_1>abc_2</step_1>
<step_2>xyz_2</step_2>
<step_3>efg_2</step_3>
<other>a3</other>
<step_4>klm_2</step_4>
</yy>
</main>
如您所見:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.