【发布时间】:2016-01-19 04:44:32
【问题描述】:
我有一个具有已定义结构但标签数量不同的 XML 文件,例如
file1.xml:
<document>
<subDoc>
<id>1</id>
<myId>1</myId>
</subDoc>
</document>
file2.xml:
<document>
<subDoc>
<id>2</id>
</subDoc>
</document>
现在我想检查一下标签myId 是否退出。所以我做了以下事情:
data = open("file1.xml",'r').read()
xml = BeautifulSoup(data)
hasAttrBs = xml.document.subdoc.has_attr('myID')
hasAttrPy = hasattr(xml.document.subdoc,'myID')
hasType = type(xml.document.subdoc.myid)
结果是 文件 1.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <class 'bs4.element.Tag'>
file2.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <type 'NoneType'>
好的,<myId> 不是<subdoc> 的属性。
但是如果存在子标签,我该如何测试呢?
//编辑:顺便说一句:我不太喜欢遍历整个子文档,因为那样会很慢。我希望找到一种方法可以直接解决/询问该元素。
【问题讨论】:
标签: python xml testing tags beautifulsoup