我有以下函数,它允许我搜索 json 并返回所搜索键的值。
但是,我试图找到正在搜索的键的实际 parentNode 并且发现这有点困难。
def bar(somejson, key):
def val(node):
# Searches for the next Element Node containing Value
e = node.nextSibling
while e and e.nodeType != e.ELEMENT_NODE:
e = e.nextSibling
return (e.getElementsByTagName('string')[0].firstChild.nodeValue if e
else None)
# parse the JSON as XML
foo_dom = parseString(xmlrpclib.dumps((json.loads(somejson),)))
# and then search all the name tags which are P1's
# and use the val user function to get the value
return [val(node) for node in foo_dom.getElementsByTagName('name')
if node.firstChild.nodeValue in key]
我尝试使用 parentNode 而不是 firstChild,但它不起作用。知道我哪里出错了吗?