<?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);
}
}