groovy – 如何确定NodeChild中给定属性的命名空间
发布时间:2020-12-14 16:22:42 所属栏目:大数据 来源:网络整理
导读:我正在尝试使用XmlSlurper解析一些 Android XML.对于给定的子节点,我想检测是否已指定具有特定命名空间的属性. 例如,在以下XML中,我想知道EditText节点是否具有声明的’b’命名空间中的任何属性: LinearLayout xmlns:android="http://schemas.android.com/a
我正在尝试使用XmlSlurper解析一些
Android XML.对于给定的子节点,我想检测是否已指定具有特定命名空间的属性.
例如,在以下XML中,我想知道EditText节点是否具有声明的’b’命名空间中的任何属性: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:b="http://x.y.z.com"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" b:enabled="true" /> </LinearLayout> 我先打电话给: def rootNode = new XmlSlurper().parseText(text) 获取根GPathResult的句柄.当我遍历孩子时,我得到了一个groovy.util.slurpersupport.NodeChild的实例.在这个类上,我可以通过调用attributes()来检查属性,在上面的EditText中,这将返回以下映射:[layout_width:“fill_parent”,layout_height:“wrap_content”,enabled:“true”]. 这一切都很好.但是,似乎没有办法查询给定属性的命名空间.我在这里错过了什么吗? 解决方法
您可以使用XmlParser而不是XmlSlurper并执行此操作:
def xml = '''<LinearLayout | xmlns:android="http://schemas.android.com/apk/res/android" | xmlns:b="http://x.y.z.com"> | | <EditText | android:layout_width="fill_parent" | android:layout_height="wrap_content" | b:enabled="true" /> |</LinearLayout>'''.stripMargin() def root = new XmlParser().parseText( xml ) root.EditText*.attributes()*.each { k,v -> println "$k.localPart $k.prefix($k.namespaceURI) = $v" } 打印出来的 layout_width android(http://schemas.android.com/apk/res/android) = fill_parent layout_height android(http://schemas.android.com/apk/res/android) = wrap_content enabled b(http://x.y.z.com) = true 编辑 要使用XmlSlurper,首先需要使用反射从根节点访问namespaceTagHints属性: def rootNode = new XmlSlurper().parseText(xml) def xmlClass = rootNode.getClass() def gpathClass = xmlClass.getSuperclass() def namespaceTagHintsField = gpathClass.getDeclaredField("namespaceTagHints") namespaceTagHintsField.setAccessible(true) def namespaceDeclarations = namespaceTagHintsField.get(rootNode) namespaceTagHints是GPathResult的属性,它是NodeChild的超类. 然后,您可以交叉引用此映射以访问命名空间前缀,并打印出与上面相同的结果: rootNode.EditText.nodeIterator().each { groovy.util.slurpersupport.Node n -> n.@attributeNamespaces.each { name,ns -> def prefix = namespaceDeclarations.find {key,value -> value == ns}.key println "$name $prefix($ns) = ${n.attributes()"$name"}" } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |