Xerces for Android异常求助:导入Maven jar包后仍报错
Hey there, sorry to hear you're hitting roadblocks with Xerces on Android—let’s walk through the most common fixes for this issue, since just importing the standard Maven jar often isn’t enough due to Android’s built-in XML parsing stack.
1. Use a Shaded Xerces Build to Avoid Class Conflicts
Android comes with its own implementation of XML parsing APIs (like org.xml.sax, javax.xml.parsers) that clash with Xerces’ bundled classes. The easiest fix is to use a shaded (package-renamed) version of Xerces, which relocates its internal packages to avoid overlap with Android’s system classes.
Add this dependency to your Maven pom.xml:
<dependency> <groupId>xerces</groupId> <artifactId>xercesImpl-shaded</artifactId> <version>2.12.2</version> <!-- Use the latest stable version --> </dependency>
2. Exclude Conflicting Transitive Dependencies
If you insist on using the standard Xerces jar, you need to exclude the xml-apis dependency (since Android already provides these classes, having duplicates causes runtime errors):
<dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.12.2</version> <exclusions> <exclusion> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> </exclusion> </exclusions> </dependency>
3. Adjust ProGuard/R8 Rules
If you’re using code obfuscation (ProGuard or R8), it’s likely stripping critical Xerces classes. Add these rules to your proguard-rules.pro file to preserve Xerces’ functionality:
# For standard Xerces -keep class org.apache.xerces.** { *; } -keep interface org.apache.xerces.** { *; } # For shaded Xerces (if using xercesImpl-shaded) -keep class org.apache.xerces_shaded.** { *; } -keep interface org.apache.xerces_shaded.** { *; }
4. Verify Runtime Class Loading
In rare cases, Android’s class loader might prioritize the system XML classes over your Xerces jar. If you’re initializing Xerces explicitly, make sure you’re referencing the correct classes from your dependency. For example, when creating a SAXParserFactory, specify Xerces’ implementation directly:
SAXParserFactory factory = SAXParserFactory.newInstance("org.apache.xerces.jaxp.SAXParserFactoryImpl", null);
(Note: Use org.apache.xerces_shaded.jaxp.SAXParserFactoryImpl if using the shaded version.)
If none of these steps resolve your issue, sharing the full exception stack trace and your build configuration (pom.xml or build.gradle) would help narrow down the exact problem.
内容的提问来源于stack exchange,提问作者John

