java类javax.xml.xpath.XPathConstants的实例源码

ComponentProfileHandler.java 文件源码 项目:uavstack 阅读 20 收藏 0 点赞 0 评论 0
/**
 * selectXMLNode
 * 
 * @param xpath
 * @return Node
 */
public Node selectXMLNode(String xpath) {

    for (Document doc : this.docs) {
        try {
            Node node = (Node) this.xpath.evaluate(xpath, doc, XPathConstants.NODE);

            if (null != node) {
                return node;
            }

        }
        catch (XPathExpressionException e) {
            if (this.logger.isLogEnabled()) {
                this.logger.warn("Select nodes[" + xpath + "] from doc[" + doc + "] FAILs.", e);
            }
        }
    }

    return null;
}
VersionFinder.java 文件源码 项目:VISNode 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Returns the version
 * 
 * @return String
 */
public static String getVersion() {
    String jarImplementation = VISNode.class.getPackage().getImplementationVersion();
    if (jarImplementation != null) {
        return jarImplementation;
    }
    String file = VISNode.class.getResource(".").getFile();
    String pack = VISNode.class.getPackage().getName().replace(".", "/") + '/';
    File pomXml = new File(file.replace("target/classes/" + pack, "pom.xml"));
    if (pomXml.exists()) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new FileReader(pomXml)));
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
        } catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }
    }
    return "Unknown version";
}
XPathSelector.java 文件源码 项目:UIAutomatorWD 阅读 15 收藏 0 点赞 0 评论 0
public NodeInfoList find(UiElement context) throws Exception {
    Element domNode = getDomNode((UiElement<?, ?>) context);
    NodeInfoList list = new NodeInfoList();
    getDocument().appendChild(domNode);
    NodeList nodes = (NodeList) xPathExpression.evaluate(domNode, XPathConstants.NODESET);
    int nodesLength = nodes.getLength();
    for (int i = 0; i < nodesLength; i++) {
        if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE && !FROM_DOM_MAP.get(nodes.item(i)).getClassName().equals("hierarchy")) {
            list.addToList(FROM_DOM_MAP.get(nodes.item(i)).node);
        }
    }
    try {
        getDocument().removeChild(domNode);
    } catch (DOMException e) {
        document = null;
    }
    return list;
}
FetchDetailsToIndex.java 文件源码 项目:openmrs-contrib-addonindex 阅读 23 收藏 0 点赞 0 评论 0
private void handleRequireModules(AddOnVersion addOnVersion, XPath xpath, Document config)
        throws XPathExpressionException {
    NodeList nodeList = (NodeList) xpath.evaluate("/module/require_modules/require_module", config,
            XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node item = nodeList.item(i);
        Node version = item.getAttributes().getNamedItem("version");
        String requiredModule = item.getTextContent().trim();
        String requiredVersion = version == null ? null : version.getTextContent().trim();
        // sometimes modules are inadvertently uploaded without substituting maven variables in config.xml and we end
        // up with a required module version like ${reportingVersion}
        if (requiredVersion != null && requiredVersion.startsWith("${")) {
            requiredVersion = null;
        }
        addOnVersion.addRequiredModule(requiredModule, requiredVersion);
    }
}
SoapMessageManager.java 文件源码 项目:verify-hub 阅读 15 收藏 0 点赞 0 评论 0
public Element unwrapSoapMessage(Element soapElement) {
    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 {
        final String expression = "/soapenv:Envelope/soapenv:Body/samlp:Response";
        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,
                    writeToString(soapElement), expression);
            LOG.error(errorMessage);
            throw new IllegalArgumentException(errorMessage);
        }

        return element;
    } catch (XPathExpressionException e) {
        throw propagate(e);
    }
}
XPathContentWorkerSelector.java 文件源码 项目:alfresco-repository 阅读 19 收藏 0 点赞 0 评论 0
/**
 * Check the given document against the list of XPath statements provided.
 * 
 * @param doc          the XML document
 * @return                  Returns a content worker that was matched or <tt>null</tt>
 */
private W processDocument(Document doc)
{
    for (Map.Entry<String, W> entry : workersByXPath.entrySet())
    {
        try
        {
            String xpath = entry.getKey();
            W worker = entry.getValue();
            // Execute the statement
            Object ret = xpathFactory.newXPath().evaluate(xpath, doc, XPathConstants.NODE);
            if (ret != null)
            {
                // We found one
                return worker;
            }
        }
        catch (XPathExpressionException e)
        {
            // We accept this and move on
        }
    }
    // Nothing found
    return null;
}
XmlUtilities.java 文件源码 项目:ats-framework 阅读 15 收藏 0 点赞 0 评论 0
/**
 * Get values matching passed XPath expression
 * @param node
 * @param expression XPath expression
 * @return matching values
 * @throws Exception
 */
private static String[] getByXpath( Node node, String expression ) throws Exception {

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpression = xPath.compile(expression);

    NodeList nlist = (NodeList) xPathExpression.evaluate(node, XPathConstants.NODESET);

    int nodeListSize = nlist.getLength();
    List<String> values = new ArrayList<String>(nodeListSize);
    for (int index = 0; index < nlist.getLength(); index++) {
        Node aNode = nlist.item(index);
        values.add(aNode.getTextContent());
    }
    return values.toArray(new String[values.size()]);
}
TableFunctions.java 文件源码 项目:JATS2LaTeX 阅读 16 收藏 0 点赞 0 评论 0
protected static void countColumns(XPath xPath, Table table, Node tableHead)
        throws XPathExpressionException, DOMException, NumberFormatException {
    if (tableHead != null) {
        Node firstRow = (Node) xPath.compile("*[1]").evaluate(tableHead, XPathConstants.NODE);
        NodeList childFirstRows = firstRow.getChildNodes();
        int columnNumber = 0;
        for (int w = 0; w < childFirstRows.getLength(); w++) {
            Node childFirstRow = childFirstRows.item(w);
            if (childFirstRow.getNodeValue() == null && (childFirstRow.getNodeName() == "th" || childFirstRow.getNodeName() == "td")) {
                int number = 1;
                if (childFirstRow.getAttributes().getNamedItem("colspan") != null) {
                    number = Integer.parseInt(childFirstRow.getAttributes().getNamedItem("colspan").getNodeValue());
                } 
                columnNumber = columnNumber + number;
            }
        }
        table.setColumnNumber(columnNumber);
    }
}
CustomMasksParser.java 文件源码 项目:mnp 阅读 20 收藏 0 点赞 0 评论 0
@Override
public void parse(Consumer<MnoInfo> consumer) throws Exception {
    File fXmlFile = config.toFile();

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    XPathExpression xpathMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mno']");
    XPathExpression xpathMasksMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mask']");
    NodeList mnoNodes = (NodeList) xpathMno.evaluate(doc, XPathConstants.NODESET);
    for (int i=0; i<mnoNodes.getLength(); i++) {
        Node node = mnoNodes.item(i);
        NamedNodeMap attributes = node.getAttributes();
        String country = getValue(attributes.getNamedItem("country"));
        String title = getValue(attributes.getNamedItem("title"));
        String area = getValue(attributes.getNamedItem("area"));
        Set<Mask> masks = new HashSet<>();
        NodeList maskNodes = (NodeList) xpathMasksMno.evaluate(doc, XPathConstants.NODESET);
        for (int j=0; j<maskNodes.getLength(); j++) {
            masks.add(Mask.parse(getValue(maskNodes.item(j))));
        }
        consumer.accept(new MnoInfo(title, area, country, masks));
    }
}
ValidationService.java 文件源码 项目:ARCLib 阅读 22 收藏 0 点赞 0 评论 0
/**
 * 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);
        }
    }
}
ValidationService.java 文件源码 项目:ARCLib 阅读 29 收藏 0 点赞 0 评论 0
/**
 * Performs all validation schema checks contained in the validation profile. If the validation has failed (some of the XMLs
 * specified in the validation profile do not match their respective validation schemas) {@link SchemaValidationError} is thrown.
 *
 * @param sipPath path to the SIP
 * @param validationProfileDoc document with the validation profile
 * @param validationProfileId id of the validation profile
 * @throws IOException if some of the XMLs address from the validation profile does not exist
 * @throws XPathExpressionException if there is an error in the XPath expression
 * @throws SAXException if the XSD schema is invalid
 */
private void performValidationSchemaChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws
        XPathExpressionException, IOException, SAXException {
    XPath xPath =  XPathFactory.newInstance().newXPath();

    NodeList nodes = (NodeList) xPath.compile("/profile/rule/validationSchemaCheck")
            .evaluate(validationProfileDoc,
                    XPathConstants.NODESET);
    for (int i = 0; i< nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        String filePath = element.getElementsByTagName("filePath").item(0).getTextContent();
        String schema = element.getElementsByTagName("schema").item(0).getTextContent();

        String absoluteFilePath = sipPath + filePath;

        try {
            ValidationChecker.validateWithXMLSchema(new FileInputStream(absoluteFilePath), new InputStream[] {
                    new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8.name()))});
        } catch (GeneralException e) {
            log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + filePath + "\" is not " +
                    "valid against its corresponding schema.");
            throw new SchemaValidationError(filePath, schema, e.getMessage());
        }
    }
}
Bug4991857.java 文件源码 项目:openjdk-jdk10 阅读 15 收藏 0 点赞 0 评论 0
@Test
public void testXPath11() throws Exception {
    try {
        Document d = null;

        XPathFactory xpathFactory = XPathFactory.newInstance();
        Assert.assertNotNull(xpathFactory);

        XPath xpath = xpathFactory.newXPath();
        Assert.assertNotNull(xpath);

        String quantity = (String) xpath.evaluate("/widgets/widget[@name='a']/@quantity", d, XPathConstants.STRING);
        Assert.fail("XPathExpressionException not thrown");
    } catch (XPathExpressionException e) {
        // Expected exception as context node is null
    }
}
DomXmlUtils.java 文件源码 项目:DaUtil 阅读 17 收藏 0 点赞 0 评论 0
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expUserTask = xpath.compile(exp);
    final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

    return new Iterator<Node>() {
        private int index = 0;

        @Override
        public Node next() {
            return nodeList.item(index++);
        }

        @Override
        public boolean hasNext() {
            return (nodeList.getLength() - index) > 0;
        }
    };
}
AddNotificationSchemaXML.java 文件源码 项目:Equella 阅读 15 收藏 0 点赞 0 评论 0
@SuppressWarnings("nls")
@Override
public void execute(TemporaryFileHandle staging, InstitutionInfo instInfo, ConverterParams params)
    throws XPathExpressionException
{
    SubTemporaryFile folder = new SubTemporaryFile(staging, "workflow");
    List<String> entries = xmlHelper.getXmlFileList(folder);
    for( String entry : entries )
    {
        PropBagEx workflow = xmlHelper.readToPropBagEx(folder, entry);
        NodeList zeroDays = (NodeList) allNodes.evaluate(workflow.getRootElement(), XPathConstants.NODESET);
        for( int i = 0; i < zeroDays.getLength(); i++ )
        {
            PropBagEx bag = new PropBagEx(zeroDays.item(i), true);
            bag.setNode("priority", Priority.NORMAL.intValue());
            if( bag.isNodeTrue("escalate") && bag.getIntNode("escalationdays") == 0 )
            {
                bag.setNode("escalate", "false");
            }
        }
        xmlHelper.writeFromPropBagEx(folder, entry, workflow);
    }
}
DOCXMergeEngine.java 文件源码 项目:doctemplate 阅读 20 收藏 0 点赞 0 评论 0
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;
    }
DomXmlUtils.java 文件源码 项目:DAFramework 阅读 21 收藏 0 点赞 0 评论 0
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expUserTask = xpath.compile(exp);
    final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

    return new Iterator<Node>() {
        private int index = 0;

        @Override
        public Node next() {
            return nodeList.item(index++);
        }

        @Override
        public boolean hasNext() {
            return (nodeList.getLength() - index) > 0;
        }
    };
}
AbstractXMLRSSTest.java 文件源码 项目:xmlrss 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void testSignThenRedactAndThenVerify() throws Exception {
    RedactableXMLSignature sig = RedactableXMLSignature.getInstance(algorithm);
    sig.initSign(keyPair);
    sig.setDocument(new FileInputStream("testdata/vehicles.xml"));
    sig.addSignSelector("#xpointer(id('a1'))", true);
    sig.addSignSelector("#xpointer(id('a2'))", true);
    sig.addSignSelector("#xpointer(id('a3'))", true);
    Document document = sig.sign();

    sig.initRedact(keyPair.getPublic());
    sig.setDocument(document);
    sig.addRedactSelector("#xpointer(id('a3'))");
    sig.redact();

    validateXSD(document);

    sig.initVerify(keyPair.getPublic());
    sig.setDocument(document);
    assertTrue(sig.verify());

    // ensure that a3 is actually removed
    XPath xPath = XPathFactory.newInstance().newXPath();
    assertNull(xPath.evaluate("//*[@id='a3']", document, XPathConstants.NODE));
    assertNull(xPath.evaluate("//*[@URI=\"#xpointer(id('a3'))\"]", document, XPathConstants.NODE));
}
SoapMessageManager.java 文件源码 项目:verify-matching-service-adapter 阅读 17 收藏 0 点赞 0 评论 0
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);
    }
}
ManifestParser.java 文件源码 项目:NBANDROID-V2 阅读 25 收藏 0 点赞 0 评论 0
private static Iterable<String> getAttrNames(InputStream is, XPathExpression expr) {
    Set<String> names = Sets.newHashSet();
    if (expr != null) {
        try {
            Document doc = parseStream(is);
            if (doc != null) {
                NodeList nodelist = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                for (int i = 0; i < nodelist.getLength(); i++) {
                    String name = nodelist.item(i).getNodeValue();
                    names.add(name);
                }
            }
        } catch (XPathExpressionException ex) {
            LOG.log(Level.WARNING, null, ex);
        }
    }
    return names;
}
OnderhoudAfnemerindicatiesBerichtParser.java 文件源码 项目:OperatieBRP 阅读 16 收藏 0 点赞 0 评论 0
@Override
protected VerzoekParser<AfnemerindicatieVerzoek> geefDienstSpecifiekeParser(final Node node) {
    try {
        final String plaatsenExpressie = SLASH + BRP_NAMESPACE_PREFIX + SoortBericht.LVG_SYN_REGISTREER_AFNEMERINDICATIE.getIdentifier()
                + SLASH + BRP_NAMESPACE_PREFIX + PLAATSING_AFNEMERINDICATIE;
        final String verwijderenExpressie = SLASH + BRP_NAMESPACE_PREFIX + SoortBericht.LVG_SYN_REGISTREER_AFNEMERINDICATIE.getIdentifier()
                + SLASH + BRP_NAMESPACE_PREFIX + VERWIJDERING_AFNEMERINDICATIE;
        final Node plaatsingNode = (Node) xpath.evaluate(plaatsenExpressie, node, XPathConstants.NODE);
        final Node verwijderingNode = (Node) xpath.evaluate(verwijderenExpressie, node, XPathConstants.NODE);
        for (Map.Entry<String, VerzoekParser<AfnemerindicatieVerzoek>> entry : DIENST_BERICHT_PARSER_MAP.entrySet()) {
            if ((plaatsingNode != null && entry.getKey().contains(plaatsingNode.getLocalName())) || (verwijderingNode != null && entry.getKey()
                    .contains(verwijderingNode.getLocalName()))) {
                return entry.getValue();
            }
        }
    } catch (final XPathExpressionException e) {
        throw new UnsupportedOperationException("XPath kon niet worden geëvalueerd.", e);
    }
    throw new BrpServiceRuntimeException("Geen geschikte parser voor dit verzoek.");
}
Framework.java 文件源码 项目:jdk8u-jdk 阅读 32 收藏 0 点赞 0 评论 0
public Framework(final String name, final File bsFile) {
    super(name, null);
    try {
        final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile();
        path = pathf.getParentFile().getParentFile().getCanonicalPath();
    } catch (IOException x) {
        throw new RuntimeException(x);
    }
    binaries = findBinaries(path, name);

    pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase();
    try {
        rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE);
    } catch (final XPathExpressionException e) { throw new RuntimeException(e); }
    protocols = new ArrayList<Protocol>();
    categories = new ArrayList<Category>();
}
CoordinatesUtil.java 文件源码 项目:C4SG-Obsolete 阅读 22 收藏 0 点赞 0 评论 0
/**@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;
  }
Pom.java 文件源码 项目:nbreleaseplugin 阅读 25 收藏 0 点赞 0 评论 0
private List<ElementValue> findElementValues(ElementValue pev, String path) {
    List<ElementValue> result = new ArrayList<>();
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        NodeList list = (NodeList) xpath.evaluate(path, pev.getElement(), XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            result.add(new ElementValue((Element) list.item(i), Type.OK));
        }
    } catch (XPathExpressionException ex) {
    }
    return result;
}
MarkupManipulator.java 文件源码 项目:qpp-conversion-tool 阅读 22 收藏 0 点赞 0 评论 0
public InputStream upsetTheNorm(String xPath, boolean remove) {
    try {
        document = dbf.newDocumentBuilder().parse(new File(pathname));
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile(xPath);

        NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
        if (searchedNodes == null) {
            System.out.println("bad path: " + xPath);
        } else {
            for (int i = 0; i < searchedNodes.getLength(); i++) {
                Node searched = searchedNodes.item(i);

                Node owningElement = (searched instanceof ElementImpl)
                        ? searched
                        : ((AttrImpl) searched).getOwnerElement();

                Node containingParent = owningElement.getParentNode();

                if (remove) {
                    containingParent.removeChild(owningElement);
                } else {
                    containingParent.appendChild(owningElement.cloneNode(true));
                }

            }
        }

        Transformer t = tf.newTransformer();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Result result = new StreamResult(os);
        t.transform(new DOMSource(document), result);
        return new ByteArrayInputStream(os.toByteArray());
    } catch (ParserConfigurationException | IOException | SAXException |
            XPathExpressionException | TransformerException ex) {
        throw new RuntimeException(ex);
    }
}
QrdaGenerator.java 文件源码 项目:qpp-conversion-tool 阅读 17 收藏 0 点赞 0 评论 0
private void removeWhitespace(Document document) throws XPathExpressionException {
    document.normalize();
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
            document,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }
}
RatReportTask.java 文件源码 项目:incubator-netbeans 阅读 20 收藏 0 点赞 0 评论 0
private void doPopulateUnapproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException {
    NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"false\"]", rootElement, XPathConstants.NODESET);
    for (int i = 0; i < evaluate.getLength(); i++) {
        String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent());
        String moduleName = getModuleName(resources);
        if (!moduleRATInfo.containsKey(moduleName)) {
            moduleRATInfo.get(NOT_CLUSTER).addUnapproved(resources);
        } else {
            moduleRATInfo.get(moduleName).addUnapproved(resources);
        }
    }
}
RatReportTask.java 文件源码 项目:incubator-netbeans 阅读 17 收藏 0 点赞 0 评论 0
private void doPopulateApproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException {
    NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"true\"]", rootElement, XPathConstants.NODESET);
    for (int i = 0; i < evaluate.getLength(); i++) {
        String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent());
        String moduleName = getModuleName(resources);
        if (!moduleRATInfo.containsKey(moduleName)) {
            moduleRATInfo.get(NOT_CLUSTER).addApproved(resources);
        } else {
            moduleRATInfo.get(moduleName).addApproved(resources);
        }

    }
}
TestFinder.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
private static void loadExcludesFile(final String testExcludesFile, final Set<String> testExcludeSet) throws XPathExpressionException {
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final NodeList testIds = (NodeList) xpath.evaluate("/excludeList/test/@id", new InputSource(testExcludesFile), XPathConstants.NODESET);
    for (int i = testIds.getLength() - 1; i >= 0; i--) {
        testExcludeSet.add(testIds.item(i).getNodeValue());
    }
}
Util.java 文件源码 项目:incubator-netbeans 阅读 21 收藏 0 点赞 0 评论 0
public static List runXPathQuery(File parsedFile, String xpathExpr) throws Exception{
    List result = new ArrayList();
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    InputSource inputSource = new InputSource(new FileInputStream(parsedFile));
    NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET);
    if((nodes != null) && (nodes.getLength() > 0)){
        for(int i=0; i<nodes.getLength();i++){
            org.w3c.dom.Node node = nodes.item(i);
            result.add(node.getNodeValue());
        }
    }
    return result;
}
SoapMessageManagerTest.java 文件源码 项目:verify-matching-service-adapter 阅读 17 收藏 0 点赞 0 评论 0
private Element getAttributeQuery(Document document) throws XPathExpressionException {
    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");
    xpath.setNamespaceContext(context);

    return (Element) xpath.evaluate("//samlp:Response", document, XPathConstants.NODE);
}


问题


面经


文章

微信
公众号

扫码关注公众号