-1

我有多个具有相似元素的 xml 文件。如何从多个文件中提取子元素?我编写了一个示例代码,它从单个文件中提取所需的元素,但我需要从多个 xml 文件中提取。这里的主要问题是它应该仅在 admin-server-name 等于 name 时打印所需的字段

#!/usr/bin/python
import commands
from xml.dom.minidom import parse
from xml.dom import minidom
import xml.dom.minidom
cmd = "find . / -name config.xml 2>/dev/null |grep -w config/config.xml"
p = commands.getoutput(cmd)
count=0;
admnprt=[]
lstnaddr=[]
dmnver=[]
admnsrvnme=[]
serverName=[]
word=p.rstrip().split('\n')
print word
print "no of domains are %s" %len(word)
for line in word :
        count =count +1
        DomTree =xml.dom.minidom.parse(line)
    domain=DomTree.documentElement
        admnprt=domain.getElementsByTagName("administration-port")
    lstnaddr=domain.getElementsByTagName("listen-address")
    admnsrvnme=domain.getElementsByTagName("admin-server-name")
    dmnver=domain.getElementsByTagName("domain-version")
    serverName = document.getElementsByTagName("name")
    if(serverName == "admnsrvnme"):
        for i in admnprt:
            print "administration-port for %s domain is " % count + " " + "%s" %i.childNodes[0].data
        for j in lstnaddr:
            print "listen-address for %s domain is " % count + " " + "%s" %j.childNodes[0].data


    for a in admnsrvnme:
        print "admin-server-name for %s domain is " % count + " " + "%s" %a.childNodes[0].data
    for b in dmnver:
        print "domain-version for %s domain is " % count + " " + "%s" %b.childNodes[0].data
4

1 回答 1

0

让您的代码运行并为所有文件调用它。

#!/usr/bin/python

import sys
from xml.dom.minidom import parse
import xml.dom.minidom

def parse_file(filename):
    DOMTree = xml.dom.minidom.parse(filename)
    domain=DOMTree.documentElement
    name=domain.getElementsByTagName("domain-version")[0]
    print" %s" % name.childNodes[0].data
    adminservername=domain.getElementsByTagName("admin-server-name")[0]
    print " %s" % adminservername.childNodes[0].data
    listenaddress=domain.getElementsByTagName("listen-address")[0]
    print " %s" % listenaddress.childNodes[0].data
    administrationport=domain.getElementsByTagName("administration-port")[0]
    print " %s" % administrationport.childNodes[0].data

for argument in sys.argv[1:] :
    parse_file(argument)

现在您可以运行具有多个文件名的脚本

yourscript.py filename1 filename2

于 2013-10-28T11:46:25.323 回答