* @param xmlPathQuery XML path pathQuery
* @param captureContent capture content, if true capture the content within an element
* @return <code>Document</code> captured XML model or null if there's no match
*/
public Document read(String xmlPathQuery, boolean captureContent) {
XmlPath xmlPath = new XmlPath(xmlPathQuery);
Document doc = new Document();
boolean captureXml = false;
try {
String localName;
XmlPathElement element;
XmlPath currentPath;
while(reader.hasNext()) {
int event = reader.next();
switch(event) {
case XMLStreamConstants.START_ELEMENT:
// element
localName = reader.getLocalName();
List<XmlPathElementAttribute> attributes = getAttributes(reader);
element = new XmlPathElement(localName, attributes);
// set current path
elementPath.add(element);
// path match?
currentPath = new XmlPath(elementPath);
if(xmlPath.equals(currentPath)) {
// found the path
captureXml = true;
}
// capture XML?
if(captureXml) {
doc.addElement(element.toString());
}
// only capture start tag?
if(! captureContent && xmlPath.equals(currentPath)) {
return doc;
}
break;
case XMLStreamConstants.CHARACTERS:
// capture XML?
if(captureXml) {
String text = reader.getText();
text = text.replace("\n", " ");
text = text.replaceAll(" {2,}", " ");
text = text.replaceAll("&", "&");
text = text.replaceAll("\"", """);
text = text.replaceAll("'", "'");
text = text.replaceAll("<", "<");
text = text.replaceAll(">", ">");
text = text.trim();
if(text.length() > 0) {
doc.addContent(text);
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// element
localName = reader.getLocalName();
element = new XmlPathElement(localName);
// capture XML?
if(captureXml) {
doc.endElement();
}
// path match?
currentPath = new XmlPath(elementPath);
if(xmlPath.equals(currentPath)) {
// found the closing path
elementPath.remove(elementPath.size() - 1);
return doc;
}