The*_*ndr 14 python xml tags testing beautifulsoup
我有一个XML文件,其中包含已定义的结构但标签数量不同,例如
file1.xml:
<document>
<subDoc>
<id>1</id>
<myId>1</myId>
</subDoc>
</document>
Run Code Online (Sandbox Code Playgroud)
file2.xml:
<document>
<subDoc>
<id>2</id>
</subDoc>
</document>
Run Code Online (Sandbox Code Playgroud)
现在我想检查标签是否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)
Run Code Online (Sandbox Code Playgroud)
结果是file1.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <class 'bs4.element.Tag'>
Run Code Online (Sandbox Code Playgroud)
file2.xml:
hasAttrBs -> False
hasAttrPy -> True
hasType -> <type 'NoneType'>
Run Code Online (Sandbox Code Playgroud)
好的,<myId>不是属性<subdoc>.
但是,如果存在子标签,我该如何测试?
//编辑:顺便说一下:我真的不喜欢通过整个子块进行迭代,因为这将非常慢.我希望找到一种可以直接解决/询问该元素的方法.
wpe*_*rcy 11
查找子标签是否存在的最简单方法很简单
childTag = xml.find('childTag')
if childTag:
# do stuff
Run Code Online (Sandbox Code Playgroud)
更具体地说,OP的问题:
如果你不知道 XML doc 的结构,你可以使用.find()汤的方法。像这样的东西:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.find("myId")
hasAttrBs2 = xml2.find("myId")
Run Code Online (Sandbox Code Playgroud)
如果您确实知道结构,则可以通过像这样访问标记名称作为属性来获取所需的元素xml.document.subdoc.myid。所以整个事情会是这样的:
with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.document.subdoc.myid
hasAttrBs2 = xml2.document.subdoc.myid
print hasAttrBs
print hasAttrBs2
Run Code Online (Sandbox Code Playgroud)
印刷
<myid>1</myid>
None
Run Code Online (Sandbox Code Playgroud)