具有限定名称的 dom4j attributeValue

dom4j attributeValue with qualified name

我正在使用 dom4j 来解析 AndroidManifestFile.xml。但是我发现它对 "android:xxx" 属性的处理很奇怪。

例如:

    <receiver android:name="ProcessOutgoingCallTest" android:exported="false"                                                                                                              
        android:enabled="false">                                                                                                                                                           
        <intent-filter android:priority="1">                                                                                                                                               
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />                                                                                                              
            <category android:name="android.intent.category.DEFAULT" />                                                                                                                    
        </intent-filter>                                                                                                                                                                   
    </receiver>

return 值 e.attributeValue("android:exported") 将是 null 但是使用 e.attributeValue("exported") 将获得正确的字符串(但我不喜欢这种方式,因为它可能匹配更多超出预期)。同时,e.attributeValue(new QName("android:exported")) 仍然是空字符串。

获取属性的正确方法是什么

android:只不过是XML中的namespace

如果只有一种可能的命名空间,写成e.attributeValue("exported").

就可以了

QName represents a qualified name value of an XML element or attribute. It consists of a local name and a Namespace instance

QName(String name)       
QName(String name, Namespace namespace)    
QName(String name, Namespace namespace, String qualifiedName) 

因此,new QName("android:exported")是错误的,正确的形式是

new QName("exported", new Namespace("android", "http://schemas.android.com/apk/res/android"))

如果您在这里错过了它的命名空间,则默认为 NO_NAMESPACE

public QName(String name) {
    this(name, Namespace.NO_NAMESPACE);
}

示例:

        Element root = document.getRootElement();
        Namespace namespace = new Namespace("android", "http://schemas.android.com/apk/res/android");
        for(Iterator i = root.elementIterator("receiver"); i.hasNext();)
        {
            Element e = (Element)i.next();
            System.out.println(e.attributeValue("exported"));
            System.out.println(e.attributeValue(new QName("exported", namespace)));
        }