我有以下解析XML文件的简单代码。问题是,如果XML文件中的名称空间包含“:”,则会出现错误。没有它,没有问题。当我从XML中删除“:”时,当我在“ Junos and Style”之间使用“:”时,就会发生这种情况。请指教。
失败:
<interface-information xmlns="http://xml.juniper.net/junos/12.1X47/junos-interface" **junos:style**="brief">
适用于:
<interface-information xmlns="http://xml.juniper.net/junos/12.1X47/junos-interface" **junosstyle**="brief">
Python脚本:
from xml.dom.minidom import parse
import xml.dom.minidom
DOMTree = xml.dom.minidom.parse("test.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("xmlns"):
print "Root element : %s" % collection.getAttribute("xmlns")
Interfaces = collection.getElementsByTagName("logical-interface")
for rname in Interfaces:
print "*****Interface*****"
rtype = rname.getElementsByTagName('name')[0]
print "Type: %s" % rtype.childNodes[0].data
这是错误:
Traceback (most recent call last):
File "test.py", line 48, in <module>
DOMTree = xml.dom.minidom.parse("test.xml")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 1921, in parse
return expatbuilder.parse(file)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 924, in parse
result = builder.parseFile(fp)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 207, in parseFile
parser.Parse(buffer, 0)
xml.parsers.expat.ExpatError: unbound prefix: line 2, column 0
在“ Junos and Style”之间的XML中不包含“:”是可行的
这是完整的XML:
<?xml version="1.0"?>
<interface-information xmlns="http://xml.juniper.net/junos/12.1X47/junos-interface" junos:style="brief">
<logical-interface>
<name>reth4.10</name>
<description>
Test description
</description>
<if-config-flags>
<iff-snmp-traps/>
<internal-flags>
0x0
</internal-flags>
</if-config-flags>
<encapsulation>
ENET2
</encapsulation>
<filter-information>
</filter-information>
<logical-interface-zone-name>
Test2
</logical-interface-zone-name>
<allowed-host-inbound-traffic>
<inbound-ping/>
</allowed-host-inbound-traffic>
<address-family>
<address-family-name>
inet
</address-family-name>
<interface-address>
</interface-address>
</address-family>
<address-family>
<address-family-name>
multiservice
</address-family-name>
</address-family>
</logical-interface>
</interface-information>
添加junos的定义显然可以解决解析问题。
<rpc-reply xmlns:junos="http://xml.juniper.net/junos/12.1X47/junos">
我已使用以下工作示例作为参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句