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:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <sheets> <sheet name="Sheet1" sheetId="1" r:id="rId1"/> </sheets> </workbook>
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]
The above is the detailed content of How to Handle XML Namespaces in Java XPath Queries?. For more information, please follow other related articles on the PHP Chinese website!