Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove comments in raw XML files with Gradle when the file is packaged

Tags:

android

gradle

My project have XML files in the raw resource directory of my Android project:

Project Layout

I would like to remove comments (<!-- ... -->) from these files when it is packaged in .apk file:

Original file sample:

<?xml version="1.0" encoding="utf-8"?>
    <celebrations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:noNamespaceSchemaLocation="celebrations_schema.xsd">

    <!-- This is a very important comment useful during development -->
    <celebration name="celebration 1" type="oneTime" ... />

    <!-- This is another very important comment useful during development -->
    <celebration name="celebration 2" type="reccurent" ... />
</celebrations>

Expected filtered file:

<?xml version="1.0" encoding="utf-8"?>
<celebrations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:noNamespaceSchemaLocation="celebrations_schema.xsd">
    <celebration name="celebration 1" type="oneTime" ... />
    <celebration name="celebration 2" type="reccurent" ... />
</celebrations>

I have found some interesting similar solutions here, but I can't manage it to work. Adding these lines in my app build.gradle

processResources {
    filesMatching('**/myxmlfiletobestrippedfromcomments.xml') {
        filter {
            String line -> line.replaceAll('<!--.*-->', '')
        }
    }
}

generates the following error:

Error:(86, 0) Gradle DSL method not found: 'processResources()'

For opening and parsing the XML file from java code, I use the following method:

InputStream definition = context.getResources().openRawResource(resId);
...
try {
    XmlPullParser parser = Xml.newPullParser();
    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    parser.setInput(definition, null);
    parser.nextTag();
    return parseCelebrations(parser);
} finally {
    definition.close();
}    
like image 354
DenisGL Avatar asked May 27 '16 23:05

DenisGL


2 Answers

Default xml‘s comment will no package into apk, you can decompile to test it.

like image 55
laomo Avatar answered Nov 16 '22 05:11

laomo


I solved my issue by moving my file to the res\xml directory. In this case, the XML file is 'compiled' and is unreadable if I open the APK archive.

However, I had to change the opening and the parsing code of my XML file, to something like this:

XmlResourceParser xmlResourceParser = context.getResources().getXml(resId);
...
// I had to add this line (to skip START_DOCUMENT tag, which was not needed
// with opening from the `raw` directory)
while (xmlResourceParser.next() != XmlPullParser.START_TAG);

return parseCelebrations(xmlResourceParser);
like image 35
DenisGL Avatar answered Nov 16 '22 03:11

DenisGL