本文整理汇总了Java中javax.xml.xpath.XPathFactory.newXPath方法的典型用法代码示例。如果您正苦于以下问题:Java XPathFactory.newXPath方法的具体用法?Java XPathFactory.newXPath怎么用?Java XPathFactory.newXPath使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.xml.xpath.XPathFactory
的用法示例。
在下文中一共展示了XPathFactory.newXPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getMaxRId
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("Relationships/*");
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
int idNum = Integer.parseInt(id.substring("rId".length()));
this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
}
return this.maxRId;
}
示例2: getValueFromStatus
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
/**
* Get value from status XML doc.
*
* @param doc Doc to get value from
* @param elementName Element name to search
* @param attribute Attribute to search
* @return The value found
* @throws XPathExpressionException Error in XPath expression
*/
public static String getValueFromStatus(final Document doc,
final String elementName,
final String attribute)
throws XPathExpressionException {
// Create XPath
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
StringBuilder expression = new StringBuilder();
// Build XPath from element name and attribute value (if exists)
expression.append("//").append(elementName);
if (attribute != null) {
expression.append("[@name=\'").append(attribute).append("\']");
}
expression.append("/text()");
XPathExpression xPathExpression = xPath.compile(expression.toString());
// Return result from XPath expression
return xPathExpression.evaluate(doc);
}
示例3: readExampleDefine
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
public static ExampleDefine readExampleDefine(InputStream in) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder dbd = dbf.newDocumentBuilder();
Document doc = dbd.parse(in);
XPathFactory f = XPathFactory.newInstance();
XPath path = f.newXPath();
Node scriptNode= (Node)path.evaluate("example/script", doc,XPathConstants.NODE);
String script = scriptNode.getTextContent().trim();
Node contextNode= (Node)path.evaluate("example/context", doc,XPathConstants.NODE);
String context = contextNode.getTextContent().trim();
return new ExampleDefine(script,context);
}
示例4: queryApi
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
/**Query the API and returns the list of expansions. Update the cache.
* @param abbrev lowercase abbreviation.
* @throws Exception
*/
private synchronized String[] queryApi(String abbrev, int retryLeft)
throws Exception {
if (retryLeft < MAX_RETRY)
Thread.sleep(1000);
URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s",
API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8")));
boolean cached = abbrToExpansion.containsKey(abbrev);
LOG.info("{} {}", cached ? "<cached>" : "Querying", url);
if (cached) return abbrToExpansion.get(abbrev);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(0);
connection.setRequestProperty("Accept", "*/*");
connection
.setRequestProperty("Content-Type", "multipart/form-data");
connection.setUseCaches(false);
if (connection.getResponseCode() != 200) {
Scanner s = new Scanner(connection.getErrorStream())
.useDelimiter("\\A");
LOG.error("Got HTTP error {}. Message is: {}",
connection.getResponseCode(), s.next());
s.close();
throw new RuntimeException("Got response code:"
+ connection.getResponseCode());
}
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
try {
doc = builder.parse(connection.getInputStream());
} catch (IOException e) {
LOG.error("Got error while querying: {}", url);
throw e;
}
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression resourceExpr = xpath.compile("//definition/text()");
NodeList resources = (NodeList) resourceExpr.evaluate(doc,
XPathConstants.NODESET);
Vector<String> resVect = new Vector<>();
for (int i=0; i<resources.getLength(); i++){
String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim();
if (!resVect.contains(expansion))
resVect.add(expansion);
}
String[] res = resVect.toArray(new String[]{});
abbrToExpansion.put(abbrev, res);
increaseFlushCounter();
return res;
}
示例5: getCoordinates
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
/**@param{Object} Address- The physical address of a location
* This method returns Geocode coordinates of the Address object.Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway,
* Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).Please give all the physical Address values
* for a precise coordinate. setting none of the values will give a null value for the Latitude and Longitude.
*/
public static GeoCode getCoordinates(Address address) throws Exception
{
GeoCode geo= new GeoCode();
String physicalAddress = (address.getAddress1() == null ? "" : address.getAddress1() + ",")
+ (address.getAddress2() == null ? "" : address.getAddress2() + ",")
+ (address.getCityName() == null ? "" : address.getCityName() + ",")
+ (address.getState() == null ? "" : address.getState() + "-")
+ (address.getZip() == null ? "" : address.getZip() + ",")
+ (address.getCountry() == null ? "" : address.getCountry());
String api = GMAPADDRESS + URLEncoder.encode(physicalAddress, "UTF-8") + SENSOR;
URL url = new URL(api);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if(responseCode == 200)
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = builder.parse(httpConnection.getInputStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(STATUS);
String status = (String)expr.evaluate(document, XPathConstants.STRING);
if(status.equals("OK"))
{
expr = xpath.compile(LATITUDE);
String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
expr = xpath.compile(LONGITUDE);
String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
geo.setLatitude(latitude);
geo.setLongitude(longitude);
}
}
else
{
throw new Exception("Fail to Convert to Geocode");
}
return geo;
}
示例6: MetaDataMerger
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
public MetaDataMerger ( final String label, final boolean compressed ) throws Exception
{
this.doc = createDocument ();
final XPathFactory xpf = XPathFactory.newInstance ();
final XPath xp = xpf.newXPath ();
this.isCategoryPathExpression = xp.compile ( "properties/property[@name='org.eclipse.equinox.p2.type.category']/@value" );
final ProcessingInstruction pi = this.doc.createProcessingInstruction ( "metadataRepository", "" );
pi.setData ( "version=\"1.1.0\"" );
this.doc.appendChild ( pi );
this.r = this.doc.createElement ( "repository" );
this.doc.appendChild ( this.r );
this.r.setAttribute ( "name", label );
this.r.setAttribute ( "type", "org.eclipse.equinox.internal.p2.metadata.repository.LocalMetadataRepository" );
this.r.setAttribute ( "version", "1" );
this.p = this.doc.createElement ( "properties" );
this.r.appendChild ( this.p );
addProperty ( this.p, "p2.compressed", "" + compressed );
addProperty ( this.p, "p2.timestamp", "" + System.currentTimeMillis () );
this.u = this.doc.createElement ( "units" );
this.r.appendChild ( this.u );
}
示例7: evaluate
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
void evaluate(boolean enableExt) throws XPathFactoryConfigurationException, XPathExpressionException {
Document document = getDocument();
XPathFactory xPathFactory = XPathFactory.newInstance();
/**
* Use of the extension function 'http://exslt.org/strings:tokenize' is
* not allowed when the secure processing feature is set to true.
* Attempt to use the new property to enable extension function
*/
if (enableExt) {
boolean isExtensionSupported = enableExtensionFunction(xPathFactory);
}
xPathFactory.setXPathFunctionResolver(new MyXPathFunctionResolver());
if (System.getSecurityManager() == null) {
xPathFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
}
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new MyNamespaceContext());
String xPathResult = xPath.evaluate(XPATH_EXPRESSION, document);
System.out.println(
"XPath result (enableExtensionFunction == " + enableExt + ") = \""
+ xPathResult
+ "\"");
}
示例8: createXPath
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private XPath createXPath() throws XPathFactoryConfigurationException {
XPathFactory xpathFactory = XPathFactory.newInstance();
Assert.assertNotNull(xpathFactory);
XPath xpath = xpathFactory.newXPath();
Assert.assertNotNull(xpath);
return xpath;
}
示例9: transform
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private String transform(Document document) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression testNameExpression = xpath.compile("//test-case/name");
NodeList testNameNodes = (NodeList) testNameExpression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < testNameNodes.getLength(); i++) {
testNameNodes.item(i).getFirstChild().setNodeValue(testNameNodes.item(i).getTextContent().replace("'", ""));
}
String xmlAfterTransform = Util.getXMLFile(document);
return xmlAfterTransform;
}
示例10: compile
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private static XPathExpression compile(String path) {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
try {
return xpath.compile(path);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例11: getConfigValue
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private static String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression userExpr = xpath.compile("smaph/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value");
return userExpr.evaluate(doc);
}
示例12: generateFiles
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private static void generateFiles(File parentDir, String testName, int byteIndex, byte[] template, String matchXPath) throws Exception {
File testDir = new File(parentDir, testName);
if(!testDir.exists() && !testDir.mkdirs()) {
throw new RuntimeException("Error creating directory " + testDir.getAbsolutePath());
}
// Initialize the heavy weight XML stuff.
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(matchXPath);
// Iterate over all possible value the current byte could have.
for(int i = 0; i <= 255; i++) {
// Generate a packet.
byte[] copy = Arrays.copyOf(template, template.length);
copy[byteIndex] = (byte) i;
File output = new File(testDir, i + ".pcapng");
FileUtils.writeByteArrayToFile(output, copy);
// Use WireShark to decode the packet to an xml form.
File decodedOutput = new File(testDir, i + ".xml");
ProcessBuilder pb = new ProcessBuilder("tshark", "-T", "pdml", "-r", output.getAbsolutePath());
pb.redirectOutput(ProcessBuilder.Redirect.to(decodedOutput));
Process process = pb.start();
process.waitFor();
// Check if a given XPath is found -> A valid parameter was found.
Document document = builder.parse(decodedOutput);
NodeList list= (NodeList) expr.evaluate(document, XPathConstants.NODESET);
// If a valid parameter is found, output that to the console.
if(list.getLength() > 0) {
String name = list.item(0).getAttributes().getNamedItem("showname").getNodeValue();
String value = list.item(0).getAttributes().getNamedItem("value").getNodeValue();
System.out.println("found option for " + testName + ": " + name + " = 0x" + value);
}
}
}
示例13: loadFromXML
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
/**
* Loads a data set from an XML file
*
* @param dataSource
* the XML file containing the data
* @param recordPath
* the XPath to the XML nodes representing the entries
* @param dataset
* the dataset to fill
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws XPathExpressionException
*/
public void loadFromXML(File dataSource,
String recordPath,
DataSet<RecordType, SchemaElementType> dataset)
throws ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
// initialise the dataset
initialiseDataset(dataset);
// create objects for reading the XML file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(dataSource);
// prepare the XPath that selects the entries
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile(recordPath);
// execute the XPath to get all entries
NodeList list = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
if (list.getLength() == 0) {
System.out.println("ERROR: no elements matching the XPath ("
+ recordPath + ") found in the input file "
+ dataSource.getAbsolutePath());
} else {
System.out.println(String.format("Loading %d elements from %s",
list.getLength(), dataSource.getName()));
// create entries from all nodes matching the XPath
for (int i = 0; i < list.getLength(); i++) {
// create the entry, use file name as provenance information
RecordType record = createModelFromElement(
list.item(i), dataSource.getName());
if (record != null) {
// add it to the data set
dataset.add(record);
} else {
System.out.println(String.format(
"Could not generate entry for ", list.item(i)
.getTextContent()));
}
}
}
}
示例14: merge
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
private String merge(String expression, List<String> files) throws Exception {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression compiledExpression = xpath.compile(expression);
return merge(compiledExpression, files);
}
示例15: getNodeList
import javax.xml.xpath.XPathFactory; //导入方法依赖的package包/类
public NodeList getNodeList(String xPathExpression) throws XPathExpressionException{
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
return (NodeList)xPath.evaluate(xPathExpression, configuration, XPathConstants.NODESET);
}