本文整理汇总了Java中javax.xml.xpath.XPathFactory类的典型用法代码示例。如果您正苦于以下问题:Java XPathFactory类的具体用法?Java XPathFactory怎么用?Java XPathFactory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
XPathFactory类属于javax.xml.xpath包,在下文中一共展示了XPathFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createXPathFactory
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Returns properly configured (e.g. security features) factory
* - securityProcessing == is set based on security processing property, default is true
*/
public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException {
try {
XPathFactory factory = XPathFactory.newInstance();
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory);
}
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
return factory;
} catch (XPathFactoryConfigurationException ex) {
LOGGER.log(Level.SEVERE, null, ex);
throw new IllegalStateException( ex);
} catch (AbstractMethodError er) {
LOGGER.log(Level.SEVERE, null, er);
throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
}
}
示例2: isMavenFXProject
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
public static boolean isMavenFXProject(@NonNull final Project prj) {
if (isMavenProject(prj)) {
try {
FileObject pomXml = prj.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(FileUtil.toFile(pomXml));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression exprJfxrt = xpath.compile("//bootclasspath[contains(text(),'jfxrt')]"); //NOI18N
XPathExpression exprFxPackager = xpath.compile("//executable[contains(text(),'javafxpackager')]"); //NOI18N
XPathExpression exprPackager = xpath.compile("//executable[contains(text(),'javapackager')]"); //NOI18N
boolean jfxrt = (Boolean) exprJfxrt.evaluate(doc, XPathConstants.BOOLEAN);
boolean packager = (Boolean) exprPackager.evaluate(doc, XPathConstants.BOOLEAN);
boolean fxPackager = (Boolean) exprFxPackager.evaluate(doc, XPathConstants.BOOLEAN);
return jfxrt && (packager || fxPackager);
} catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException ex) {
LOGGER.log(Level.INFO, "Error while parsing pom.xml.", ex); //NOI18N
return false;
}
}
return false;
}
示例3: testAddLibraries
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
public void testAddLibraries() throws Exception {
SuiteProject suite = TestBase.generateSuite(getWorkDir(), "suite");
TestBase.generateSuiteComponent(suite, "lib");
TestBase.generateSuiteComponent(suite, "testlib");
NbModuleProject clientprj = TestBase.generateSuiteComponent(suite, "client");
Library lib = LibraryFactory.createLibrary(new LibImpl("lib"));
FileObject src = clientprj.getSourceDirectory();
assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE));
assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE));
Library testlib = LibraryFactory.createLibrary(new LibImpl("testlib"));
FileObject testsrc = clientprj.getTestSourceDirectory("unit");
assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE));
assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE));
InputSource input = new InputSource(clientprj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString());
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(nbmNamespaceContext());
assertEquals("org.example.client", xpath.evaluate("//nbm:data/nbm:code-name-base", input)); // control
assertEquals("org.example.lib", xpath.evaluate("//nbm:module-dependencies/*/nbm:code-name-base", input));
assertEquals("org.example.testlib", xpath.evaluate("//nbm:test-dependencies/*/*/nbm:code-name-base", input));
}
示例4: testAddRoots
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
public void testAddRoots() throws Exception {
NbModuleProject prj = TestBase.generateStandaloneModule(getWorkDir(), "module");
FileObject src = prj.getSourceDirectory();
FileObject jar = TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "a.jar", "entry:contents");
URL root = FileUtil.getArchiveRoot(jar.toURL());
assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
FileObject releaseModulesExt = prj.getProjectDirectory().getFileObject("release/modules/ext");
assertNotNull(releaseModulesExt);
assertNotNull(releaseModulesExt.getFileObject("a.jar"));
jar = TestFileUtils.writeZipFile(releaseModulesExt, "b.jar", "entry2:contents");
root = FileUtil.getArchiveRoot(jar.toURL());
assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE));
assertEquals(2, releaseModulesExt.getChildren().length);
String projectXml = prj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString();
InputSource input = new InputSource(projectXml);
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(nbmNamespaceContext());
assertEquals(projectXml, "ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:runtime-relative-path", input));
assertEquals(projectXml, "release/modules/ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:binary-origin", input));
assertEquals(projectXml, "ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:runtime-relative-path", input));
assertEquals(projectXml, "release/modules/ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:binary-origin", input));
}
示例5: mapPom
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/** Extract specific POM-related values from a XML-String into a map. */
Map<String, String> mapPom(String pom) {
try {
var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
var document = builder.parse(new InputSource(new StringReader(pom)));
var xpath = XPathFactory.newInstance().newXPath();
var name = xpath.evaluate("/project/name", document);
var url = xpath.evaluate("/project/url", document);
var group = xpath.evaluate("/project/groupId", document);
var artifact = xpath.evaluate("/project/artifactId", document);
var version = xpath.evaluate("/project/version", document);
if (group.isEmpty()) {
group = xpath.evaluate("/project/parent/groupId", document);
}
if (version.isEmpty()) {
version = xpath.evaluate("/project/parent/version", document);
}
return Map.of(
"name", name, "url", url, "group", group, "artifact", artifact, "version", version);
} catch (Exception e) {
debug("scan({0}) failed: {0}", pom, e);
}
return Map.of();
}
示例6: testXPath_DOM_withSM
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void testXPath_DOM_withSM() {
System.out.println("Evaluate DOM Source; Security Manager is set:");
setSystemProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl");
try {
XPathFactory xPathFactory = XPathFactory.newInstance("http://java.sun.com/jaxp/xpath/dom",
"com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null);
xPathFactory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true);
if ((boolean) xPathFactory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) {
Assert.fail("should not override in secure mode");
}
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
clearSystemProperty(DOM_FACTORY_ID);
}
}
示例7: testXPath13
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
@Test
public void testXPath13() throws Exception {
QName qname = new QName(XMLConstants.XML_NS_URI, "");
XPathFactory xpathFactory = XPathFactory.newInstance();
Assert.assertNotNull(xpathFactory);
XPath xpath = xpathFactory.newXPath();
Assert.assertNotNull(xpath);
try {
xpath.evaluate("1+1", (Object) null, qname);
Assert.fail("failed , expected IAE not thrown");
} catch (IllegalArgumentException e) {
; // as expected
}
}
示例8: findElementValue
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Find the element reference for the selected element. The selected element
* is an XPATH expression relation to the element reference given as a
* parameter.
*
* @param pev the element reference from which the XPATH expression is
* evaluated.
* @param path the XPATH expression
* @return the resulting element reference
*/
public final ElementValue findElementValue(ElementValue pev, String path) {
XPath xpath = XPathFactory.newInstance().newXPath();
try {
Element el = (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE);
return pev.isInHerited()
? (el == null
? new ElementValue(Type.INHERITED_MISSING)
: new ElementValue(el, Type.INHERITED))
: (el == null
? new ElementValue(pev, path)
: new ElementValue(el, Type.OK));
} catch (XPathExpressionException ex) {
return new ElementValue(pev, path);
}
}
示例9: XPathMetadataExtracter
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Default constructor
*/
public XPathMetadataExtracter()
{
super(new HashSet<String>(Arrays.asList(SUPPORTED_MIMETYPES)));
try
{
DocumentBuilderFactory normalFactory = DocumentBuilderFactory.newInstance();
documentBuilder = normalFactory.newDocumentBuilder();
DocumentBuilderFactory dtdIgnoringFactory = DocumentBuilderFactory.newInstance();
dtdIgnoringFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dtdIgnoringFactory.setFeature("http://xml.org/sax/features/validation", false);
dtdIgnoringDocumentBuilder = dtdIgnoringFactory.newDocumentBuilder();
xpathFactory = XPathFactory.newInstance();
}
catch (Throwable e)
{
throw new AlfrescoRuntimeException("Failed to initialize XML metadata extractor", e);
}
}
示例10: countNodes
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Count nodes which are given via xpath expression
*/
public static Double countNodes(Node node, String nodePath)
throws XPathExpressionException {
final XPathFactory factory = XPathFactory.newInstance();
final XPath xpath = factory.newXPath();
final XPathExpression expr = xpath.compile("count(" + nodePath + ')');
return (Double) expr.evaluate(node, XPathConstants.NUMBER);
}
示例11: eval
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
public boolean eval() throws BuildException {
if (nullOrEmpty(fileName)) {
throw new BuildException("No file set");
}
File file = new File(fileName);
if (!file.exists() || file.isDirectory()) {
throw new BuildException(
"The specified file does not exist or is a directory");
}
if (nullOrEmpty(path)) {
throw new BuildException("No XPath expression set");
}
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource(fileName);
Boolean result = Boolean.FALSE;
try {
result = (Boolean) xpath.evaluate(path, inputSource,
XPathConstants.BOOLEAN);
} catch (XPathExpressionException e) {
throw new BuildException("XPath expression fails", e);
}
return result.booleanValue();
}
示例12: setJKSLocation
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
private void setJKSLocation(String domainPath) {
URL fileUrl = Thread.currentThread().getContextClassLoader()
.getResource(STSConfigTemplateFileName);
File file = new File(fileUrl.getFile());
if (!file.exists()) {
System.out.println("MockSTSServiceTemplate.xml not exists");
return;
}
try {
Document doc = parse(file);
XPathFactory xpfactory = XPathFactory.newInstance();
XPath path = xpfactory.newXPath();
updateElementValue(path, doc,
"/definitions/Policy/ExactlyOne/All/KeyStore", "location",
domainPath + "/config/keystore.jks");
updateElementValue(path, doc,
"/definitions/Policy/ExactlyOne/All/TrustStore",
"location", domainPath + "/config/cacerts.jks");
doc2Xml(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
示例13: unwrapSoapMessage
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
private Element unwrapSoapMessage(Element soapElement, SamlElementType samlElementType) {
XPath xpath = XPathFactory.newInstance().newXPath();
NamespaceContextImpl context = new NamespaceContextImpl();
context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#");
xpath.setNamespaceContext(context);
try {
String expression = "//samlp:" + samlElementType.getElementName();
Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE);
if (element == null) {
String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE,
XmlUtils.writeToString(soapElement), expression);
LOG.error(errorMessage);
throw new SoapUnwrappingException(errorMessage);
}
return element;
} catch (XPathExpressionException e) {
throw propagate(e);
}
}
示例14: performFileExistenceChecks
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Performs all file existence checks contained in the validation profile. If the validation has failed (some of the files specified
* in the validation profile do not exist), {@link MissingFile} exception is thrown.
*
* @param sipPath path to the SIP
* @param validationProfileDoc document with the validation profile
* @param validationProfileId id of the validation profile
* @throws XPathExpressionException if there is an error in the XPath expression
*/
private void performFileExistenceChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.compile("/profile/rule/fileExistenceCheck")
.evaluate(validationProfileDoc, XPathConstants.NODESET);
for (int i = 0; i< nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String relativePath = element.getElementsByTagName("filePath").item(0).getTextContent();
String absolutePath = sipPath + relativePath;
if (!ValidationChecker.fileExists(absolutePath)) {
log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + relativePath + "\" is missing.");
throw new MissingFile(relativePath, validationProfileId);
}
}
}
示例15: findWithXPath
import javax.xml.xpath.XPathFactory; //导入依赖的package包/类
/**
* Searches XML element with XPath and returns list of nodes found
*
* @param xml input stream with the XML in which the element is being searched
* @param expression XPath expression used in search
* @return {@link NodeList} of elements matching the XPath in the XML
* @throws XPathExpressionException if there is an error in the XPath expression
* @throws IOException if the XML at the specified path is missing
* @throws SAXException if the XML cannot be parsed
* @throws ParserConfigurationException
*/
public static NodeList findWithXPath(InputStream xml, String expression)
throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
try {
return (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new InvalidXPathException(expression, e);
}
}