下面列出了javax.xml.xpath.XPath#compile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Retrieves a list of dependencies of the given scope
*/
public static List<String> getDependencies(String pom, String scope) throws Exception {
String expression = "/project/dependencies/dependency[scope='" + scope + "']";
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(pom);
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(expression);
List<String> dependencies = new LinkedList<>();
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
try (StringWriter writer = new StringWriter()) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(writer));
String xml = writer.toString();
dependencies.add(xml);
}
}
return dependencies;
}
private Node findFirstElementByName(String name, Document doc) {
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
try {
XPathExpression expr = xpath.compile("//*[@name='" + name + "']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if (nodes == null || nodes.getLength() < 1) {
return null;
}
return nodes.item(0);
} catch (XPathExpressionException e) {
log.error("Error occurred while finding element " + name + "in given document", e);
return null;
}
}
public List<String> xmlToList(String path, Document xmlDocument)
throws Ovm3ResourceException {
List<String> list = new ArrayList<String>();
XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
XPath xPath = factory.newXPath();
try {
XPathExpression xPathExpression = xPath.compile(path);
NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument,
XPathConstants.NODESET);
for (int ind = 0; ind < nodeList.getLength(); ind++) {
if (!nodeList.item(ind).getNodeValue().isEmpty()) {
list.add("" + nodeList.item(ind).getNodeValue());
} else {
list.add("" + nodeList.item(ind).getNodeValue());
}
}
return list;
} catch (XPathExpressionException e) {
throw new Ovm3ResourceException("Problem parsing XML to List: ", e);
}
}
/**
* Returns the xml value.
*
* @param sIn
* @param sxpath
* @return
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws XPathExpressionException
*/
public static String XPathValueFromString(String sIn, String sxpath)
throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
// DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
Document doc = loadXMLFromString(sIn);
XPath xPath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xPath.compile(sxpath);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
String sReturn = "";
for (int i = 0; i < nodes.getLength(); i++) {
sReturn = nodes.item(i).getNodeValue();
}
return sReturn;
}
/**
* Set the ID Attribute in an XML Document so that java recognises the ID
* Attribute as a real id
*
* @param document
* Document to set the ids
*/
public void setIDAttribute(Document document) {
try {
if(Thread.currentThread().getContextClassLoader() == null){
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
}
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//*[@ID]");
NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Element elem = (Element) nodeList.item(i);
Attr attr = (Attr) elem.getAttributes().getNamedItem("ID");
elem.setIdAttributeNode(attr, true);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
public String hasTopic(Document doc) {
String topic;
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
XPathExpression xPathExpression;
try {
xPathExpression = xPath.compile("/feed/link[@rel='self']/@href");
topic = xPathExpression.evaluate(doc);
if ((topic == null) || (topic.length() == 0)) {
xPathExpression = xPath.compile("//link[@rel='self']/@href");
topic = xPathExpression.evaluate(doc);
}
if (topic.length() == 0) {
return null;
}
return topic;
} catch (XPathExpressionException e) {
LOGGER.error("Invalid XpathExpression", e);
return null;
}
}
private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpathExpression);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
return nodes;
}
public void query() throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
// standard for reading an XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
XPathExpression expr = null;
builder = factory.newDocumentBuilder();
doc = builder.parse("Person.xml");
// create an XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
// create an XPath object
XPath xpath = xFactory.newXPath();
// compile the XPath expression
expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
// run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
// cast the result to a DOM NodeList
NodeList nodes = (NodeList) result;
for (int i=0; i<nodes.getLength();i++){
System.out.println(nodes.item(i).getNodeValue());
}
// new XPath expression to get the number of people with name Lars
expr = xpath.compile("count(//person[firstname='Lars'])");
// run the query and get the number of nodes
Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
System.out.println("Number of objects " +number);
// do we have more than 2 people with name Lars?
expr = xpath.compile("count(//person[firstname='Lars']) >2");
// run the query and get the number of nodes
Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
System.out.println(check);
}
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) {
if (isExportedFromAdonis50(bpmnModel)) {
Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>();
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new Bpmn20NamespaceContext());
for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) {
String elementId = entry.getKey();
DiagramNode elementBounds = entry.getValue();
String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])";
try {
XPathExpression xPathExpression = xPath.compile(expression);
String elementLocalName = xPathExpression.evaluate(bpmnModel);
if (!"participant".equals(elementLocalName)
&& !"lane".equals(elementLocalName)
&& !"textAnnotation".equals(elementLocalName)
&& !"group".equals(elementLocalName)) {
elementBounds.setX(elementBounds.getX() - elementBounds.getWidth()/2);
elementBounds.setY(elementBounds.getY() - elementBounds.getHeight()/2);
}
} catch (XPathExpressionException e) {
throw new ProcessEngineException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e);
}
mapOfFixedBounds.put(elementId, elementBounds);
}
return mapOfFixedBounds;
} else {
return elementBoundsFromBpmnDi;
}
}
public static Document merge(String expression,
InputStream... inputStreams) throws Exception {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression compiledExpression = xpath
.compile(expression);
return merge(compiledExpression, inputStreams);
}
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) {
if (isExportedFromAdonis50(bpmnModel)) {
Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>();
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new Bpmn20NamespaceContext());
for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) {
String elementId = entry.getKey();
DiagramNode elementBounds = entry.getValue();
String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])";
try {
XPathExpression xPathExpression = xPath.compile(expression);
String elementLocalName = xPathExpression.evaluate(bpmnModel);
if (!"participant".equals(elementLocalName) && !"lane".equals(elementLocalName) && !"textAnnotation".equals(elementLocalName) && !"group".equals(elementLocalName)) {
elementBounds.setX(elementBounds.getX() - elementBounds.getWidth() / 2);
elementBounds.setY(elementBounds.getY() - elementBounds.getHeight() / 2);
}
} catch (XPathExpressionException e) {
throw new ActivitiException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e);
}
mapOfFixedBounds.put(elementId, elementBounds);
}
return mapOfFixedBounds;
} else {
return elementBoundsFromBpmnDi;
}
}
private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpathExpression);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
return nodes;
}
@Override
public void filter(String URL, byte[] content, DocumentFragment doc,
ParseResult parse) {
InputStream stream = new ByteArrayInputStream(content);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
Document document = factory.newDocumentBuilder().parse(stream);
Element root = document.getDocumentElement();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile("//url");
NodeList nodes = (NodeList) expression.evaluate(root,
XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
expression = xPath.compile("loc");
Node child = (Node) expression.evaluate(node,
XPathConstants.NODE);
// create a subdocument for each url found in the sitemap
ParseData parseData = parse.get(child.getTextContent());
NodeList childs = node.getChildNodes();
for (int j = 0; j < childs.getLength(); j++) {
Node n = childs.item(j);
parseData.put(n.getNodeName(), n.getTextContent());
}
}
} catch (Exception e) {
LOG.error("Error processing sitemap from {}: {}", URL, e);
}
}
private String evaluateExpression(String expression) {
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(expression);
String version = expr.evaluate(new InputSource(new FileReader("pom.xml")));
return version;
}
catch (Exception ex) {
throw new IllegalStateException("Failed to evaluate expression", ex);
}
}
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) {
if (isExportedFromAdonis50(bpmnModel)) {
Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>();
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new Bpmn20NamespaceContext());
for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) {
String elementId = entry.getKey();
DiagramNode elementBounds = entry.getValue();
String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])";
try {
XPathExpression xPathExpression = xPath.compile(expression);
String elementLocalName = xPathExpression.evaluate(bpmnModel);
if (!"participant".equals(elementLocalName)
&& !"lane".equals(elementLocalName)
&& !"textAnnotation".equals(elementLocalName)
&& !"group".equals(elementLocalName)) {
elementBounds.setX(elementBounds.getX() - elementBounds.getWidth()/2);
elementBounds.setY(elementBounds.getY() - elementBounds.getHeight()/2);
}
} catch (XPathExpressionException e) {
throw new ActivitiException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e);
}
mapOfFixedBounds.put(elementId, elementBounds);
}
return mapOfFixedBounds;
} else {
return elementBoundsFromBpmnDi;
}
}
@Test
public void allActionsShouldBePresentInSchemeWithDefaultBuildConfigurations() throws Exception {
ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder();
PBXTarget rootTarget =
new PBXNativeTarget("rootRule", AbstractPBXObjectFactory.DefaultFactory());
rootTarget.setGlobalID("rootGID");
rootTarget.setProductReference(
new PBXFileReference(
"root.a", "root.a", PBXReference.SourceTree.BUILT_PRODUCTS_DIR, Optional.empty()));
rootTarget.setProductType(ProductTypes.STATIC_LIBRARY);
Path pbxprojectPath = Paths.get("foo/Foo.xcodeproj/project.pbxproj");
targetToProjectPathMapBuilder.put(rootTarget, pbxprojectPath);
SchemeGenerator schemeGenerator =
new SchemeGenerator(
projectFilesystem,
Optional.of(rootTarget),
ImmutableSet.of(rootTarget),
ImmutableSet.of(),
ImmutableSet.of(),
"TestScheme",
Paths.get("_gen/Foo.xcworkspace/scshareddata/xcshemes"),
false /* parallelizeBuild */,
Optional.empty() /* wasCreatedForAppExtension */,
Optional.empty() /* runnablePath */,
Optional.empty() /* remoteRunnablePath */,
SchemeActionType.DEFAULT_CONFIG_NAMES,
targetToProjectPathMapBuilder.build(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
XCScheme.LaunchAction.LaunchStyle.AUTO,
Optional.empty(), /* watchAdapter */
Optional.empty() /* notificationPayloadFile */);
Path schemePath = schemeGenerator.writeScheme();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document scheme = dBuilder.parse(projectFilesystem.newFileInputStream(schemePath));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath schemeChildrenXPath = xpathFactory.newXPath();
XPathExpression schemeChildrenExpr = schemeChildrenXPath.compile("/Scheme/node()");
NodeList actions = (NodeList) schemeChildrenExpr.evaluate(scheme, XPathConstants.NODESET);
assertThat(actions.getLength(), equalTo(6));
Node buildAction = actions.item(0);
assertThat(buildAction.getNodeName(), equalTo("BuildAction"));
assertThat(buildAction.getAttributes().getNamedItem("buildConfiguration"), nullValue());
Node testAction = actions.item(1);
assertThat(testAction.getNodeName(), equalTo("TestAction"));
assertThat(
testAction.getAttributes().getNamedItem("buildConfiguration").getNodeValue(),
equalTo("Debug"));
Node launchAction = actions.item(2);
assertThat(launchAction.getNodeName(), equalTo("LaunchAction"));
assertThat(
launchAction.getAttributes().getNamedItem("buildConfiguration").getNodeValue(),
equalTo("Debug"));
Node profileAction = actions.item(3);
assertThat(profileAction.getNodeName(), equalTo("ProfileAction"));
assertThat(
profileAction.getAttributes().getNamedItem("buildConfiguration").getNodeValue(),
equalTo("Release"));
Node analyzeAction = actions.item(4);
assertThat(analyzeAction.getNodeName(), equalTo("AnalyzeAction"));
assertThat(
analyzeAction.getAttributes().getNamedItem("buildConfiguration").getNodeValue(),
equalTo("Debug"));
Node archiveAction = actions.item(5);
assertThat(archiveAction.getNodeName(), equalTo("ArchiveAction"));
assertThat(
archiveAction.getAttributes().getNamedItem("buildConfiguration").getNodeValue(),
equalTo("Release"));
}
@Test(dataProvider = "xpath")
public void test03(XPath xpath) throws XPathExpressionException {
XPathExpression exp = xpath.compile("1+1");
int result = exp.evaluateExpression((Object)null, Integer.class);
assertTrue(result == 2);
}
protected void verifySignatureAlgorithms(Document signedDoc, AssertionInfoMap aim) throws Exception {
final AssertionInfo assertInfo = aim.get(SP12Constants.ASYMMETRIC_BINDING).iterator().next();
assertNotNull(assertInfo);
final AsymmetricBinding binding = (AsymmetricBinding) assertInfo.getAssertion();
final String expectedSignatureMethod = binding.getAlgorithmSuite().getAsymmetricSignature();
final String expectedDigestAlgorithm = binding.getAlgorithmSuite().getDigest();
final String expectedCanonAlgorithm = binding.getAlgorithmSuite().getInclusiveC14n();
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
final NamespaceContext nsContext = this.getNamespaceContext();
xpath.setNamespaceContext(nsContext);
// Signature Algorithm
final XPathExpression sigAlgoExpr =
xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo"
+ "/ds:SignatureMethod/@Algorithm");
final String sigMethod = (String) sigAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
assertEquals(expectedSignatureMethod, sigMethod);
// Digest Method Algorithm
final XPathExpression digestAlgoExpr = xpath.compile(
"/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod");
final NodeList digestMethodNodes =
(NodeList) digestAlgoExpr.evaluate(signedDoc, XPathConstants.NODESET);
for (int i = 0; i < digestMethodNodes.getLength(); i++) {
Node node = (Node)digestMethodNodes.item(i);
String digestAlgorithm = node.getAttributes().getNamedItem("Algorithm").getNodeValue();
assertEquals(expectedDigestAlgorithm, digestAlgorithm);
}
// Canonicalization Algorithm
final XPathExpression canonAlgoExpr =
xpath.compile("/s:Envelope/s:Header/wsse:Security/ds:Signature/ds:SignedInfo"
+ "/ds:CanonicalizationMethod/@Algorithm");
final String canonMethod = (String) canonAlgoExpr.evaluate(signedDoc, XPathConstants.STRING);
assertEquals(expectedCanonAlgorithm, canonMethod);
}
/** {@inheritDoc} */
@Override
public KeyFrameMeta loadKeyFrameMeta(File file) {
String filename = file.getAbsolutePath() + ".meta";
File metadataFile = new File(filename);
if (!metadataFile.exists()) {
// No such metadata
return null;
}
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
dom = db.parse(filename);
db.reset();
} catch (ParserConfigurationException pce) {
log.error("Could not parse XML file.", pce);
return null;
} catch (SAXException se) {
log.error("Could not parse XML file.", se);
return null;
} catch (IOException ioe) {
log.error("Could not parse XML file.", ioe);
return null;
}
Element root = dom.getDocumentElement();
// Check if .xml file is valid and for this .flv file
if (!"FrameMetadata".equals(root.getNodeName())) {
// Invalid XML
return null;
}
String modified = root.getAttribute("modified");
if (modified == null || !modified.equals(String.valueOf(file.lastModified()))) {
// File has changed in the meantime
return null;
}
if (!root.hasAttribute("duration")) {
// Old file without duration informations
return null;
}
if (!root.hasAttribute("audioOnly")) {
// Old file without audio/video informations
return null;
}
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
NodeList keyFrames;
try {
XPathExpression xexpr = xpath.compile("/FrameMetadata/KeyFrame");
keyFrames = (NodeList) xexpr.evaluate(dom, XPathConstants.NODESET);
} catch (XPathExpressionException err) {
log.error("could not compile xpath expression", err);
return null;
}
int length = keyFrames.getLength();
if (keyFrames == null || length == 0) {
// File doesn't contain informations about keyframes
return null;
}
KeyFrameMeta result = new KeyFrameMeta();
result.duration = Long.parseLong(root.getAttribute("duration"));
result.positions = new long[length];
result.timestamps = new int[length];
for (int i = 0; i < length; i++) {
Node node = keyFrames.item(i);
NamedNodeMap attrs = node.getAttributes();
result.positions[i] = Long.parseLong(attrs.getNamedItem("position").getNodeValue());
result.timestamps[i] = Integer.parseInt(attrs.getNamedItem("timestamp").getNodeValue());
}
result.audioOnly = "true".equals(root.getAttribute("audioOnly"));
return result;
}
/**
* Extracts the text content from text fields in a patent XML document.
*
* @param docBuilder A document builder to use when constructing intermediate XML/HTML documents in the extraction
* process.
* @param paths A list of XPath paths from which to exactract text.
* @param xpath An XPath instance to use when running XPath queries.
* @param doc The XML document from which to extract text.
* @return A list of strings representing the textual content of the document. These could be sentences,
* paragraphs, or larger text units, but should represent some sort of structure in the document's text.
* @throws ParserConfigurationException
* @throws TransformerConfigurationException
* @throws TransformerException
* @throws XPathExpressionException
*/
private static List<String> getRelevantDocumentText(DocumentBuilder docBuilder, String[] paths,
XPath xpath, Document doc)
throws ParserConfigurationException, TransformerConfigurationException,
TransformerException, XPathExpressionException {
List<String> allTextList = new ArrayList<>(0);
for (String path : paths) {
XPathExpression exp = xpath.compile(path);
NodeList textNodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
allTextList.addAll(extractTextFromHTML(docBuilder, textNodes));
}
return allTextList;
}