XML Namespace Handling in Java XPath Queries
In Java, when querying XML with XPath, namespaces can present a challenge. When XML contains no namespaces, XPath queries can be straightforward, but the presence of namespaces introduces complexities.
Case 1: XML Without Namespaces
For XML without namespaces, XPath queries use the default namespace, which is effectively no namespace. In this case, queries like "/workbook/sheets/sheet[1]" can easily retrieve elements.
Case 2: XML With Namespaces
However, XML with namespaces like the following adds complexity:
In such cases, the XPath expression "/workbook/sheets/sheet[1]" will fail because the elements are bound to the "http://schemas.openxmlformats.org/spreadsheetml/2006/main" namespace.
Solutions:
/*[local-name()='workbook' and namespace-uri()='http://schemas.openxmlformats.org/spreadsheetml/2006/main'] /*[local-name()='sheets' and namespace-uri()='http://schemas.openxmlformats.org/spreadsheetml/2006/main'] /*[local-name()='sheet' and namespace-uri()='http://schemas.openxmlformats.org/spreadsheetml/2006/main'][1]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3