protected List<String> getDistributionFilenames() {
   File distributionMPFile = new File(distributionMPDir, PACKAGES_XML);
   List<String> md5Filenames = new ArrayList<String>();
   // Try to get md5 files from packages.xml
   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
   docFactory.setNamespaceAware(true);
   try {
     DocumentBuilder builder = docFactory.newDocumentBuilder();
     Document doc = builder.parse(distributionMPFile);
     XPathFactory xpFactory = XPathFactory.newInstance();
     XPath xpath = xpFactory.newXPath();
     XPathExpression expr = xpath.compile("//package/@md5");
     NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
     for (int i = 0; i < nodes.getLength(); i++) {
       String md5 = nodes.item(i).getNodeValue();
       if ((md5 != null) && (md5.length() > 0)) {
         md5Filenames.add(md5);
       }
     }
   } catch (Exception e) {
     // Parsing failed - return empty list
     log.error("Failed parsing " + distributionMPFile, e);
     return new ArrayList<String>();
   }
   return md5Filenames;
 }
Example #2
0
  public Object resolveReference(
      Object referencedObject,
      Node elementWithReference,
      String referenceString,
      Map<String, Object> referencedObjects,
      List<ForwardReferences> forwardRefs)
      throws XPathExpressionException, IllegalArgumentException, SecurityException,
          InstantiationException, IllegalAccessException, InvocationTargetException,
          NoSuchMethodException, ParseException {
    XPathExpression exp = xpath.compile(referenceString);
    Log.i("resolveRef", "xpath evaluated for :" + referenceString);
    Element refferredElement = (Element) exp.evaluate(elementWithReference, XPathConstants.NODE);
    if (refferredElement == null) {
      throw new ParseException("Element by reference not found");
    }
    String xpathFromRoot = ParserUtil.getElementXpath(refferredElement);
    Object object = referencedObjects.get(xpathFromRoot);
    if (object == null) {
      referencedObject = objectGetter.getobjectOfClass(referencedObject.getClass(), "");
      ForwardReferences forwardRef = new ForwardReferences(referencedObject, xpathFromRoot, null);
      forwardRefs.add(forwardRef);

    } else {
      referencedObject = object;
    }
    return referencedObject;
  }
Example #3
0
  @Override
  public Layer load(Element elem, ImportSupport support, ProgressMonitor progressMonitor)
      throws IOException, IllegalDataException {
    String version = elem.getAttribute("version");
    if (!"0.1".equals(version)) {
      throw new IllegalDataException(
          tr(
              "Version ''{0}'' of meta data for osm data layer is not supported. Expected: 0.1",
              version));
    }
    try {
      XPathFactory xPathFactory = XPathFactory.newInstance();
      XPath xpath = xPathFactory.newXPath();
      XPathExpression fileExp = xpath.compile("file/text()");
      String fileStr = (String) fileExp.evaluate(elem, XPathConstants.STRING);
      if (fileStr == null || fileStr.isEmpty()) {
        throw new IllegalDataException(
            tr("File name expected for layer no. {0}", support.getLayerIndex()));
      }

      OsmImporter importer = new OsmImporter();
      try (InputStream in = support.getInputStream(fileStr)) {
        OsmImporter.OsmImporterData importData =
            importer.loadLayer(
                in, support.getFile(fileStr), support.getLayerName(), progressMonitor);

        support.addPostLayersTask(importData.getPostLayerTask());
        return importData.getLayer();
      }
    } catch (XPathExpressionException e) {
      throw new RuntimeException(e);
    }
  }
Example #4
0
	public NodeList запросNodes(String запрос) throws XPathExpressionException {

		XPathExpression выражение;
		выражение = xPath.compile(запрос);
		return (NodeList) выражение.evaluate(документ.getDocumentElement(),
				XPathConstants.NODESET);
	}
  public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath)
      throws XPathExpressionException {

    List<String> list = new ArrayList<String>();
    XPathFactory factory = XPathFactory.newInstance();

    // 2. Use the XPathFactory to create a new XPath object
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(nsc);

    // 3. Compile an XPath string into an XPathExpression
    XPathExpression expression = xpath.compile(exprString);

    // 4. Evaluate the XPath expression on an input document
    Node result =
        (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE);

    String svcName = null;
    NamedNodeMap attMap = result.getAttributes();
    Node att = attMap.getNamedItem("group");
    if (att != null) svcName = att.getNodeValue();
    if (result != null) {
      list.add(result.getNodeName());
      list.add(result.getTextContent());
      list.add(svcName);
    }
    factory = null;
    xpath = null;
    expression = null;
    result = null;
    attMap = null;
    att = null;
    return list;
  }
  public NodeList getHeaderRows() throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    // docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(file);

    NodeList sheetLst = doc.getElementsByTagName("ss:Name");

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr =
        xpath.compile("//Worksheet[@Name=\"" + sheetName + "\"]/Table/Row[1]/Cell");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList headerNodes = (NodeList) result;

    Node toRem = (Node) headerNodes.item(0);
    for (int i = 0; i < sheetLst.getLength(); i++) {
      List lstFields = new ArrayList<Node>();
      List lstFields_common = new ArrayList<Node>();
      log.debug("======================start=======================");
      Node testSuiteNode = sheetLst.item(i);
      NamedNodeMap commonAttributesList = testSuiteNode.getAttributes();
    }

    return headerNodes;
  }
Example #7
0
  public static void main(String[] args)
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
          TransformerFactoryConfigurationError, TransformerException {
    DocumentBuilder bud = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    InputStream inp = new ByteArrayInputStream(xml.getBytes());

    Document doc = bud.parse(inp);

    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//Person/PostalCode");

    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
      System.out.println(nodes.item(i).getTextContent());
      nodes.item(i).setTextContent("Ala ma kota " + i);
    }

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    StringWriter bufor = new StringWriter();
    xformer.transform(new DOMSource(doc), new StreamResult(bufor));
    System.out.println("===================");
    System.out.println(bufor.toString());
  }
Example #8
0
  public String extractInfoObjectIdentifier(String infoObjectResponse) {

    String reportId = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // dbf.setNamespaceAware(true);
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile("//info-object");
      Object result = expr.evaluate(doc, XPathConstants.NODESET);

      NodeList nodes = (NodeList) result;
      Node item = nodes.item(0);
      if (item != null) {
        NamedNodeMap attributesMap = item.getAttributes();
        Node idAttribute = attributesMap.getNamedItem("id");
        reportId = idAttribute.getNodeValue();
      }

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

    return reportId;
  }
Example #9
0
	public Double запрос„исла(String запрос) throws XPathExpressionException {

		XPathExpression выражение;
		выражение = xPath.compile(запрос);
		return (Double) выражение.evaluate(документ.getDocumentElement(),
				XPathConstants.NUMBER);
	}
 private NodeList getNodeList(Object element, String xPathExp) throws XPathExpressionException {
   XPathFactory factory = XPathFactory.newInstance();
   XPath xpath = factory.newXPath();
   XPathExpression expr = xpath.compile(xPathExp);
   Object obj = expr.evaluate(element, XPathConstants.NODESET);
   return obj instanceof NodeList ? (NodeList) obj : null;
 }
  private String fromXmlToColor(String xml) {
    String result = BLUE;
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = null;
    try {
      builder = domFactory.newDocumentBuilder();

      Document document = builder.parse(new InputSource(new StringReader(xml)));

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile("//color");

      Object n = expr.evaluate(document, XPathConstants.NODESET);
      NodeList nodes = (NodeList) n;
      if (nodes.getLength() > 0) {
        result = (String) nodes.item(0).getTextContent();
      }

    } catch (Exception e) {
      System.err.println("fromXmlToColor:" + e);
    }
    return result;
  }
  public NodeList getOQasNodeList()
      throws SAXException, ParserConfigurationException, XPathExpressionException {
    NodeList result = null;
    if (oqUrl == null) {
      logger.warn("OQ.url not found. Synchronization impossible.");
      trace.append("Синхронизация невозможна: OQ.url не указан.");
      return result;
    }
    try {
      URLConnection oqc = oqUrl.openConnection();
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true);
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document doc = builder.parse(oqc.getInputStream());
      XPath xpath = XPathFactory.newInstance().newXPath();
      XPathExpression expr = xpath.compile("/root/projects/project");
      result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (IOException e) { // обрабатываем только IOException - остальные выбрасываем наверх
      logger.error("oq project sync error: ", e);
      trace
          .append(
              "Синхронизация прервана из-за ошибки ввода/вывода при попытке получить и прочитать файл "
                  + "синхронизации: ")
          .append(e.getMessage())
          .append("\n");
    }

    return result;
  }
  public static void main(String[] args) {

    CodeExtractor myCode = new CodeExtractor(4);
    // myCode.parseFile("http://java.sun.com/docs/books/tutorial/java/nutsandbolts/for.html");
    myCode.parseFile("http://www.javadeveloper.co.in/java-example/java-hashmap-example.html");

    String docString = myCode.getDoc();
    try {
      XPath xPath = XPathFactory.newInstance().newXPath();
      XPathExpression nodeXPathExpr =
          xPath.compile("/codesnippets/text | /codesnippets/sourcecode");
      InputSource inputSource = new InputSource(new ByteArrayInputStream(docString.getBytes()));

      NodeList allNodes = (NodeList) nodeXPathExpr.evaluate(inputSource, XPathConstants.NODESET);

      int nodeNumber = allNodes.getLength();
      System.out.println("Text Found:: " + nodeNumber + " nodes.");
      System.out.println("========================================");

      for (int i = 0; i < nodeNumber; i++) {
        Node node = allNodes.item(i);

        String content = node.getTextContent();
        // content = StringEscapeUtils.unescapeHtml(content).trim();
        System.out.println(node + ":--->:" + node.getNodeName());
        if (node.getTextContent() != null) System.out.println("--->" + content);
        System.out.println("========================================");
      }

    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
  }
  /**
   * Takes an XML file containing parameterised queries + parameter queries and substitutes
   * parameters for values, then saves the resulting queries
   *
   * @param queryFileName the XML query file
   * @param queryMixFile
   * @param ignoreFile
   */
  public void generateQueries(String queryFileName, String queryMixFile, String ignoreFile) {
    File queryFile = new File(queryFileName);
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(queryFile);

      XPath xpath = XPathFactory.newInstance().newXPath();
      XPathExpression expr = xpath.compile("/queries/query");
      Object result = expr.evaluate(doc, XPathConstants.NODESET);
      NodeList nodes = (NodeList) result;

      // for each query, generate a map of parameter names and values
      //            then replace the parameters in the final query with the respective (randomly
      // selected) values
      for (int i = 0; i < nodes.getLength(); i++) {
        queryCount = i + 1;
        String completeQuery = generateCompleteQuery(nodes.item(i), doc);
        saveCompleteQuery(completeQuery);
      }
      saveHelperFiles(queryMixFile, ignoreFile);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public PositionTester(String uri, int line, int col)
      throws IOException, SAXException, XPathExpressionException {

    InputStream is = new FileInputStream(new File(uri));
    Document document = PositionalXMLReader.readXML(is);

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    XPathExpression expr = xpath.compile("//*");
    Object result = expr.evaluate(document, XPathConstants.NODESET);

    NodeList allNodes = (NodeList) result;
    int i = 0;
    Node node;
    while (allNodes.item(i) != null) {
      node = allNodes.item(i);
      i++;
      int ln = (Integer) node.getUserData("lineNumber");
      int cn = (Integer) node.getUserData("columnNumber");
      if (line == ln && col == cn) {
        element = node;
        break;
      }
    }
  }
    @Override
    public Object invokeXpathProjection(
        final InvocationContext invocationContext, final Object proxy, final Object[] args)
        throws Throwable {

      //            try {
      //                if (ReflectionHelper.mayProvideParameterNames()) {
      //                    xPath.setXPathVariableResolver(new MethodParamVariableResolver(method,
      // args, xPath.getXPathVariableResolver()));
      //               }

      final XPathExpression expression = invocationContext.getxPathExpression();
      NodeList nodes = (NodeList) expression.evaluate(node, XPathConstants.NODESET);
      int count = 0;
      for (int i = 0; i < nodes.getLength(); ++i) {
        if (Node.ATTRIBUTE_NODE == nodes.item(i).getNodeType()) {
          Attr attr = (Attr) nodes.item(i);
          attr.getOwnerElement().removeAttributeNode(attr);
          ++count;
          continue;
        }
        Node parentNode = nodes.item(i).getParentNode();
        if (parentNode == null) {
          continue;
        }
        parentNode.removeChild(nodes.item(i));
        ++count;
      }
      return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(count));
      //            } finally {
      //                xPath.reset();
      //            }
    }
Example #17
0
  private Integer fromCitation(Document doc, XPath xpath) {
    try {
      XPathExpression expr = xpath.compile("//p");
      NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

      for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node classNode = node.getAttributes().getNamedItem("class");
        if (classNode == null) continue;
        String pClass = classNode.getTextContent();
        if (pClass.equalsIgnoreCase("case_cite")) {
          String citationString = node.getTextContent();
          Matcher citationYearMatcher = citationYearPattern.matcher(citationString);
          boolean foundDate = citationYearMatcher.matches();
          if (foundDate) {
            String yearString = citationYearMatcher.group(1).toString();
            return Integer.parseInt(yearString);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Example #18
0
  /**
   * Get container window
   *
   * <p>
   *
   * @return String
   */
  private String getWindowName(String sWidgetID) {

    String sWindowName = null;
    // get widget ID
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    Object result;
    NodeList nodes;
    try {
      String xpathExpression =
          "/GUIStructure/GUI[Container//Property[Name=\""
              + GUITARConstants.ID_TAG_NAME
              + "\" and Value=\""
              + sWidgetID
              + "\"]]/Window/Attributes/Property[Name=\""
              + GUITARConstants.TITLE_TAG_NAME
              + "\"]/Value/text()";
      expr = xpath.compile(xpathExpression);
      result = expr.evaluate(docGUI, XPathConstants.NODESET);
      nodes = (NodeList) result;
      if (nodes.getLength() > 0) sWindowName = nodes.item(0).getNodeValue();
    } catch (XPathExpressionException e) {
      GUITARLog.log.error(e);
    }
    return sWindowName;
  }
Example #19
0
  public static void readXpath()
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("D:\\temp\\test_2\\screen_2.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    // XPathExpression expr = xpath
    // .compile("//Screens/Screen[@number='1']/Button[@number='1']/Action[@type='onclick']/*");
    String xpathStr = "//Screen[@number='2007']/Button[@number='87'][@h='1']";
    XPathExpression expr = xpath.compile(xpathStr);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap nodeMap = nodes.item(i).getAttributes();
      String attrName = "";
      for (int j = 0; j < nodeMap.getLength(); j++) {
        attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("="));
        if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) {
          System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue());
        }
      }
    }
  }
 private void checkBomVersionInPom(String xml) {
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   try {
     builder = factory.newDocumentBuilder();
     doc = builder.parse(new InputSource(new StringReader(xml)));
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   }
   XPathFactory xPathfactory = XPathFactory.newInstance();
   XPath xpath = xPathfactory.newXPath();
   XPathExpression expr = null;
   String bom_version = null;
   try {
     expr = xpath.compile("/project/properties/version.jboss.bom");
     bom_version = (String) expr.evaluate(doc, XPathConstants.STRING);
   } catch (XPathExpressionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   assertEquals(
       "jboss bom version in pom differs from the one given by wizard", version, bom_version);
 }
Example #21
0
	public Boolean запросЋогический(String запрос)
			throws XPathExpressionException {

		XPathExpression выражение;
		выражение = xPath.compile(запрос);
		return Boolean.valueOf((String) выражение.evaluate(документ
				.getDocumentElement(), XPathConstants.STRING));
	}
Example #22
0
	public String запрос—троки(String запрос) throws XPathExpressionException {

		XPathExpression выражение;
		выражение = xPath.compile(запрос);
		return (String) выражение.evaluate(документ.getDocumentElement(),
				XPathConstants.STRING);

	}
Example #23
0
	public Boolean запрос—уществовани¤(String запрос)
			throws XPathExpressionException {

		XPathExpression выражение;
		выражение = xPath.compile(запрос);
		return (Boolean) выражение.evaluate(документ.getDocumentElement(),
				XPathConstants.BOOLEAN);
	}
  private Element findElementByXpath(String expr, String source) throws Exception {
    String xml = JsonXmlUtil.toXml(new JSONObject(source));
    InputSource is = new InputSource(new StringReader(xml));
    XPath xPath = XPathFactory.newInstance().newXPath();

    XPathExpression xpathExpr = xPath.compile(expr);
    return (Element) xpathExpr.evaluate(is, XPathConstants.NODE);
  }
 /**
  * Evaluate xpath expression and return nodes
  *
  * @param xpathExpr
  * @return
  */
 public NodeList getNodes(String xpathExpr) {
   try {
     XPathExpression expr = xpath.compile(xpathExpr);
     return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
   } catch (XPathExpressionException e) {
     return null;
   }
 }
 /**
  * Checks if there is a servlet element with specified Servlet name.
  *
  * @param servletName Servlet name to check.
  * @return <code>true</code> if servle with specified name is present, <code>false</code>
  *     otherwise.
  */
 public boolean isAppletDefined(String appletAID) {
   try {
     XPathExpression xPression =
         xPath.compile("/applet-app/applet/applet-AID[text()='" + appletAID + "']"); // NOI18N
     return (Boolean) xPression.evaluate(doc, XPathConstants.BOOLEAN);
   } catch (XPathExpressionException ex) {
     return false;
   }
 }
Example #27
0
  protected boolean configureFilters(Node xmlDom) throws Exception {

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList filtersNodes =
        (NodeList) xpath.evaluate("/web-app/filter", xmlDom, XPathConstants.NODESET);

    // Check if josso is already installed
    XPathExpression jossoFilterClassExp =
        xpath.compile(
            "/web-app/filter[filter-class='org.josso.liferay5.agent.LiferaySSOAgentFilter']");
    Node jossoFilterNode = (Node) jossoFilterClassExp.evaluate(xmlDom, XPathConstants.NODE);

    // Append josso filter after auto-login filter in web.xml
    if (jossoFilterNode != null) {
      getPrinter()
          .printActionWarnStatus(
              "Configure",
              "JOSSO SSO Filter",
              "Already configured : "
                  + (jossoFilterNode != null ? jossoFilterNode.getNodeValue() : "<unknown>"));
      return false;
    }

    // Find auto-filter node in web.xml
    // Append josso filter after auto-login filter in web.xml

    if (filtersNodes != null && filtersNodes.getLength() > 0) {
      String xupdJossoFilter =
          "\n\t<xupdate:insert-after select=\"/web-app/filter[filter-class='com.liferay.portal.servlet.filters.autologin.AutoLoginFilter']\" >\n"
              + "\t\t<xupdate:element name=\"filter\"> \n"
              + "\t\t\t<xupdate:element name=\"filter-name\">SSO Josso Filter</xupdate:element>\n"
              + "\t\t\t<xupdate:element name=\"filter-class\">org.josso.liferay5.agent.LiferaySSOAgentFilter</xupdate:element>\n"
              + "\t\t</xupdate:element>\n"
              + "\t</xupdate:insert-after>\n\n"
              + "\t<xupdate:insert-before select=\"/web-app/filter-mapping[1]\" >\n"
              + "\t\t<xupdate:element name=\"filter-mapping\">\n"
              + "\t\t\t<filter-name>SSO Josso Filter</filter-name>\n"
              + "\t\t\t<url-pattern>/*</url-pattern>\n"
              + "\t\t</xupdate:element>\n"
              + "\t</xupdate:insert-before>";

      String qry = XUpdateUtil.XUPDATE_START + xupdJossoFilter + XUpdateUtil.XUPDATE_END;
      log.debug("XUPDATE QUERY: \n" + qry);
      XUpdateQuery xq = new XUpdateQueryImpl();
      xq.setQString(qry);
      xq.execute(xmlDom);

      getPrinter()
          .printActionOkStatus(
              "Added josso filter into web.xml", "JOSSO Liferay 5 Agent ", "WEB-INF/web.xml");

      return true;
    }
    return false;
  }
Example #28
0
  /**
   * Query Xml according to standard Xpath Query. author: zhangyutao create on 2014-03-04
   *
   * @param respXmlByte like a body of http format response
   * @param xpathQuery xpath
   * @throws ParserConfigurationException Parser Configuration Exception
   * @return NodeList
   * @throws XPathExpressionException
   */
  public static NodeList queryXml(byte[] respXmlByte, String xpathQuery) throws Exception {
    XPathFactory xfactory = XPathFactory.newInstance();
    XPath xpath = xfactory.newXPath();
    NodeList result = null;

    Document doc = stringToDoc(respXmlByte);
    XPathExpression path = xpath.compile(xpathQuery);
    result = (NodeList) path.evaluate(doc, XPathConstants.NODESET);

    return result;
  }
Example #29
0
 /**
  * This will get a List of Nodes for a given xpath
  *
  * @param path
  * @param doc
  * @return
  */
 protected NodeList getNodeListByXPath(String path, Document doc) {
   try {
     XPathFactory factory = XPathFactory.newInstance();
     XPath xpath = factory.newXPath();
     XPathExpression expr = xpath.compile(path);
     return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Example #30
0
  private String getNodeValue(XPathFactory factory, Document doc, String xpathStr)
      throws XPathExpressionException {
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(xpathStr);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList results = (NodeList) result;

    if (results.getLength() > 0 && null != results.item(0)) return results.item(0).getNodeValue();

    return null;
  }