2015-11-20 29 views
3

我使用dom4j來解析AndroidManifestFile.xml。然而,我發現它奇怪地對待「android:xxx」屬性。具有限定名稱的dom4j attributeValue

例如:

<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> 

返回值e.attributeValue("android:exported")null但是使用e.attributeValue("exported")將獲得正確的字符串(但我不喜歡這種方式,因爲它可以匹配超過預期)。同時,e.attributeValue(new QName("android:exported"))仍然是空字符串。

什麼是正確的方式來獲得屬性

回答

2

android:只不過是一個XML格式的namespace更多。

如果只有一個可能的命名空間,那麼可以寫e.attributeValue("exported")

QName表示XML元素或屬性的限定名稱值。它由一個本地名稱和一個命名空間的實例

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))); 
     } 
+0

是因爲它 「的xmlns:機器人=」?http://schemas.android.com/apk/res/android」在典型的AndroidManifest.xml定義 –

+0

是。你只需要考慮如何使用'QName'和命名空間相關的東西。 – chenzhongpu