一个好的解决方案是先将这些查询加载到地图,然后再根据地图访问它。要将查询加载到地图,您可以执行以下操作:
Map<String, String> queriesMap = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
ByteArrayInputStream inputStream = new ByteArrayInputStream("<queries> <query id=\"getUserByName\"> select * from users where name=? </query> <query id=\"getUserByEmail\"> select * from users where email=? </query></queries>".getBytes());
// you could use something like: new FileInputStream("queries.xml");
Document doc = documentBuilder.parse(inputStream);
// get queries elements
NodeList queriesNodes = doc.getElementsByTagName("queries");
// iterate over it
for (int i = 0; i < queriesNodes.getLength(); i++) {
// get queries element
Node node = queriesNodes.item(i);
// get query elements (theoretically)
NodeList queryNodes = node.getChildNodes();
for (int j = 0; j < queryNodes.getLength(); j++) {
Node queryNode = queryNodes.item(j);
// if not element just skip to next one (in case of text nodes for the white spaces)
if (!(queryNode.getNodeType() == Node.ELEMENT_NODE)) {
continue;
}
// get query
Node idAttr = queryNode.getAttributes().getNamedItem("id");
if (idAttr != null) {
queriesMap.put(idAttr.getTextContent(), StringUtils.trim(queryNode.getTextContent()));
}
}
}
System.out.println(queriesMap);