讀取 XML 檔更新後再寫入

XML 檔案範例

<add> <doc> <field name="id">48ff2f210ed74732910f168add079338</field> <field name="sku">ABC</field> <field name="name">Activity Based Costing</field> <field name="description">

An accounting system that measures the cost and performance of specific activities performed within an organisation.

For example, an ABC approach might measure the cost incurred by the accounts receivable department in handling calls for billing errors,

whereas the traditional accounting approach ignores the activity and measures

the cost of the accounts receivable department as a percentage of revenue.

</field> </doc> </add>

程式碼

# -*- coding: utf-8 -*- import sys import uuid import xml.etree.ElementTree as ET def updateTag(xmlFile): tree = ET.parse(xmlFile) root = tree.getroot() for doc in root.findall('doc'): id = doc.find("field/[@name='id']") id.text = str(uuid.uuid4()).replace('-','') sku = doc.find("field/[@name='sku']") print "%s(%s)" % (sku.text, id.text) tree.write(xmlFile) if len(sys.argv) == 1: for iFile in sys.stdin: updateTag(iFile.strip()) elif len(sys.argv) > 1: updateTag(sys.argv[1])

執行範例

  1. python updateID [XML 檔案]
  2. ls *.xml | python updateID