dom4j解析和修改xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.helloworld"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="9" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.helloworld.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


上面這是要解析的xml,需求是想要修改android:versionCode的值。
manifest是root節點,package, versionCode是manifest的attribute(屬性)。uses-sdk和application是manifest的element。

不多說了,直接上代碼


public static void main(String[] args) {
        test();
    }

    public static void test() {
    	String fileName = "/Volumes/Macintosh HD/Leo/Desktop/AndroidManifest.xml";
        try {
            SAXReader reader = new SAXReader();
            InputStream in = null;
			try {
				in = new FileInputStream(fileName);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
            Document doc = reader.read(in);
            Element root = doc.getRootElement();
            
            print(root);
            
            
            System.out.println(root.getName()+" "+root.attributeValue("versionCode"));
            Attribute attr = root.attribute("versionCode");
            System.out.println(attr.getName()+" "+attr.getValue());
            attr.setValue("123");  //修改屬性值
            try{
                /** 將document中的內容寫入文件中 */
                XMLWriter writer = new XMLWriter(new FileWriter(new File(fileName)));
                writer.write(doc);
                writer.close();
             }catch(Exception ex){
                ex.printStackTrace();
             }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    
    private static void print(Element root){//遞歸打印
    	System.out.println(root.getName());
        for (Iterator i = root.attributeIterator(); i.hasNext(); ) {
        	Attribute item = (Attribute)i.next();
        	System.out.println(item.getName()+"="+item.getValue()+" "+root.getText());  
         }
        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            print(element);
         }
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章