[英]Update an XML document using Python or a shell script
我有一个XML文件,用作具有以下结构的动态面板的索引:
<?xml version="1.0"?>
<Addons>
<line>
<text>My collection 1</text>
<level>3</level>
<comment/>
<file>Collection1.zip</file>
<size>120</size>
<parent>Collection</parent>
<directory>picture</directory>
<type>jpeg</type>
<filedate>22/05/2014</filedate>
</line>
<line>
<text>My collection 2</text>
<level>3</level>
<comment/>
<file>Collection2.zip</file>
<size>880</size>
<parent>Collection</parent>
<directory>picture</directory>
<type>jpeg</type>
<filedate>01/04/2013</filedate>
</line>
</Addons>
我的面板使用此文件作为构建索引。 当我更新服务器上的文件时,我需要手动更新filedate
元素,...但文件有80行,这很糟糕。
脚本是否有办法完成这项工作? 顺序是:
<file>
元素中读取文件名 <filedate>
元素(如果存在) 服务器上提供了Shell脚本和Python。
谢谢!!
使用xmlstarlet
命令行工具:
xmlstarlet sel -t -v '//file' -n file.xml |
while IFS= read -r filename; do
filedate=$(date -d "@$(stat -c %Y "$filename")" +%d/%m/%Y)
xmlstarlet ed --inplace -u "//filedate[../file = '$filename']" -v "$filedate" file.xml
done
这是一个小python脚本,为您做到这一点:
#!/usr/bin/python
import re
from datetime import date
input_file = open("input.xml", "r")
output_file = open("output.xml", "w")
today = date.today().strftime("%d/%m/%Y")
replacement = '<filedate>' + today + '</filedate>'
for line in input_file:
updated_line = re.sub(r'<filedate>.*?</filedate>', replacement, line)
output_file.write(updated_line)
input_file.close()
output_file.close()
一种Python解决方案,它使用XML解析器 ( xml.etree
)来稳健地处理输入:
#!/usr/bin/env python
import os
import datetime
from xml.etree import ElementTree
inFile = "in.xml"
outFile = "out.xml"
# Parse the entire document.
tree = ElementTree.parse(inFile)
# Loop over the <line> elements
for elem in tree.iter('line'):
# Get the child element [values] of interest.
fname = elem.find('file').text.strip()
elemFDate = elem.find('filedate')
# Determine the new modification date.
# Note: As @glenn jackman notes, %Y-%m-%d would be a better date format to use.
newDate = datetime.datetime.fromtimestamp(os.path.getmtime(fname)) \
.strftime("%d/%m/%y")
# Update the date element.
elemFDate.text = newDate
# Write the output file.
tree.write(outFile)
注意:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.