My project have XML files in the raw resource directory of my Android project:
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();
}
Default xml‘s comment will no package into apk, you can decompile to test it.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With