如何解析android activity_main.xml文件并对其进行修改?

时间:2015-07-01 13:05:38

标签: java android xml parsing

我想解析android activity_main.xml并以实用的方式添加我的视图的自定义属性标记。

例如:(原创)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <view
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        class="com.test.compoundviewcreation.Slider"
        android:id="@+id/view4"/>
</RelativeLayout>

修改后:(自定义:添加了sliderLabel标记)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <view
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        class="com.test.compoundviewcreation.Slider"
        android:id="@+id/view4"
        custom:sliderLabel="Custom SLider Label"/>
</RelativeLayout>

我尝试使用DOM Parser但它无法解析它并显示xml doc为null。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Sale导入的joox库,例如:

compile 'org.jooq:joox:1.3.0'

然后,您可以使用find()方法获取所有<view>元素和attr()方法来分配您的自定义属性,例如:

import java.io.File;
import java.io.IOException;

import org.joox.Match;
import org.xml.sax.SAXException;
import static org.joox.JOOX.$;

public class Main {

    public static void main(String[] args) throws SAXException, IOException {
        final Match $m = $(new File(args[0]));
        $m.find("view").attr("custom:sliderLabel", "Custom SLider Label");
        $m.write(System.out);
    }
}

我将假设您的xml格式正确(与您的示例不同)并且您将xml文件作为参数提供给程序。我还添加了另一个<view>来表明它会改变它们。

请注意,输出既没有格式良好,也没有排序(属性),但这不是xml问题。结果:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_height="match_parent" android:layout_width="match_parent">

    <view android:id="@+id/view4" android:layout_height="wrap_content" android:layout_width="match_parent" class="com.test.compoundviewcreation.Slider" custom:sliderLabel="Custom SLider Label"/>

    <view android:id="@+id/view5" android:layout_height="wrap_content" android:layout_width="match_parent" class="com.test.compoundviewcreation.Slider" custom:sliderLabel="Custom SLider Label"/>

</RelativeLayout>

更新:根据评论,假设您只希望将新属性附加到<view> id view4的{​​{1}},则需要使用名称空间。我更喜欢用xpath()方法处理这些情况,例如:

public static void main(String[] args) throws IOException, SAXException {
    final Match $m = $(new File(args[0]));
    $m.namespace("android", "http://schemas.android.com/apk/res/android")
            .xpath("//view[@android:id='@+id/view4']")
            .attr("custom:sliderLabel", "Custom SLider Label");
    $m.write(System.out);
}
相关问题