我有一个xml文件,我需要添加数据,我尝试使用sed。任何人都可以帮我解决我做错的地方。
我有一个像这样的xml文件:
<!DOCTYPE sf-migration
PUBLIC "-//VA Software, Inc.//DTD SourceForge Migration 1.0//EN"
"/opt/add-ons/import-6.1/dtd/sf-migration_1_0.dtd">
<sf-migration toVersion="6.1.0.0" fromVersion="5.0.0.0">
<users></users>
</sf-migration>
现在我需要在用户中添加以下文件:
<sfuser xid="user1000">
<username>beq03838</username>
<email>noreply@nxp.com</email>
<alternateEmail1></alternateEmail1>
<dateCreated>2016-12-20 14:02:23 CET</dateCreated>
<dateLastModified>2016-12-20 14:02:23 CET</dateLastModified>
<detail></detail>
<monitoringPreference>email</monitoringPreference>
<lastLogin></lastLogin>
</sfuser>
我的输出应该如下:
enter <!DOCTYPE sf-migration
PUBLIC "-//VA Software, Inc.//DTD SourceForge Migration 1.0//EN"
"/opt/add-ons/import-6.1/dtd/sf-migration_1_0.dtd">
<sf-migration toVersion="6.1.0.0" fromVersion="5.0.0.0">
<users>
<sfuser xid="user1000">
<username>beq03838</username>
<email>noreply@nxp.com</email>
<alternateEmail1></alternateEmail1>
<dateCreated>2016-12-20 14:02:23 CET</dateCreated>
<dateLastModified>2016-12-20 14:02:23 CET</dateLastModified>
<lastLogin></lastLogin>
</sfuser>
</users>
</sf-migration>
我使用下面的shell脚本来附加文本:
CONTENT=give the suer content
C=$(echo $CONTENT | sed 's/\//\\\//g')
sed "/<\/users>/ s/.*/${C}\n&/" /tmptest/user1.xml
我做错了什么?有没有其他简单的方法在xml中添加元素? 我需要在shell中完成,因为我的完整代码在shell中
答案 0 :(得分:0)
使用多个文件并在命令行中转义是非常容易出错和hacky。在大多数语言中,您可以使用非常小的脚本实现相同的功能。这是Python 2中的一个例子:
template = open("user.xml").read()
snippet = open("user_data.xml").read()
result = template.replace("</users>", snippet + "</users>")
open("user.xml", "w").write(result)
输出:
<!DOCTYPE sf-migration PUBLIC "-//VA Software, Inc.//DTD SourceForge Migration 1.0//EN" "/opt/add-ons/import-6.1/dtd/sf-migration_1_0.dtd"> <sf-migration toVersion="6.1.0.0" fromVersion="5.0.0.0">
<users>
<sfuser xid="user1000">
<username>beq03838</username>
<email>noreply@nxp.com</email>
<alternateEmail1></alternateEmail1>
<dateCreated>2016-12-20 14:02:23 CET</dateCreated>
<dateLastModified>2016-12-20 14:02:23 CET</dateLastModified>
<detail></detail>
<monitoringPreference>email</monitoringPreference>
<lastLogin></lastLogin>
</sfuser>
</users>
如果您需要更频繁地执行此操作,请使用以下脚本:
#!/usr/bin/python
import sys
if len(sys.argv) != 4:
print "This script prepends the given pattern in a template with a snippet. Both snippet and template are files."
print "Usage:"
print sys.argv[0] + " template snippet replacementpattern"
sys.exit(1)
template = open(sys.argv[1]).read()
snippet = open(sys.argv[2]).read()
pattern = sys.argv[3]
if not pattern in template:
print "Template doesn't contain the pattern."
sys.exit(2)
print template.replace(pattern, snippet + pattern)
用法:
./prepend.py template.xml snippet.xml "</users>"