从python访问xml文件中的内部元素

时间:2019-03-01 07:56:38

标签: python python-3.x

我有下面的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<appcmd>
   <APP path="/" APP.NAME="test1" pool="Pool1">
      <application name="app1">
         <virtualDirectory />
         <virtualDirectory path="/" physicalPath="c:\test" />
      </application>
   </APP>

   <APP path="/" APP.NAME="test1" pool="Pool1">
      <application name="app1">
         <virtualDirectory />
         <virtualDirectory path="/" physicalPath="c:\test" />
      </application>
   </APP>
</appcmd>

下面是尝试访问应用程序名称属性的代码:

from xml.dom import minidom
mydoc = minidom.parse('ex1.xml')
apps = mydoc.getElementsByTagName('APP')
print(mydoc.nodeName)
print(mydoc.firstChild.tagName)
for app in apps:
    app_path = app.getAttribute('path')
    print(app_path)
    application_pool = app.getAttribute('application')['name']
    print(application_pool)

我遇到以下错误:

Traceback (most recent call last):
#document
  File "C:/py372/files/readxml1.py", line 9, in <module>
    application_pool = app.getAttribute('application')['name']
appcmd
TypeError: string indices must be integers
/

Process finished with exit code 1

任何人都可以帮助我如何访问应用程序和virtualDirectory属性

1 个答案:

答案 0 :(得分:0)

代替

application_pool = app.getAttribute('application')['name']

我在下面使用了代码,因为节点name中没有属性application,首先需要找到包含.getElementByTagName()的属性的节点,然后才能访问它的属性。

for names in app.getElementsByTagName('application'):
        print(names.getAttribute('name'))

这给了我这样的输出:

#document
appcmd
/
app1
/
app1

P.S。这是我的第一个答案:)希望它足够好:)