Java Code Examples for org.w3c.dom.NodeList

The following are top voted examples for showing how to use org.w3c.dom.NodeList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: JPEGMetadata.java   Source Code and License 9 votes vote down vote up
private void mergeStandardTextNode(Node node)
    throws IIOInvalidTreeException {
    // Convert to comments.  For the moment ignore the encoding issue.
    // Ignore keywords, language, and encoding (for the moment).
    // If compression tag is present, use only entries with "none".
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        NamedNodeMap attrs = child.getAttributes();
        Node comp = attrs.getNamedItem("compression");
        boolean copyIt = true;
        if (comp != null) {
            String compString = comp.getNodeValue();
            if (!compString.equals("none")) {
                copyIt = false;
            }
        }
        if (copyIt) {
            String value = attrs.getNamedItem("value").getNodeValue();
            COMMarkerSegment com = new COMMarkerSegment(value);
            insertCOMMarkerSegment(com);
        }
    }
}
 
Example 2
Project: org.mybatis.generator.core-1.3.5   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 7 votes vote down vote up
protected void parseCommentGenerator(Context context, Node node) {
    CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();

    context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type"); //$NON-NLS-1$

    if (stringHasValue(type)) {
        commentGeneratorConfiguration.setConfigurationType(type);
    }

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(commentGeneratorConfiguration, childNode);
        }
    }
}
 
Example 3
Project: openjdk-jdk10   File: XMLSchemaInternalizationLogic.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new XML Schema element of the given local name
 * and insert it as the first child of the given parent node.
 *
 * @return
 *      Newly create element.
 */
private Element insertXMLSchemaElement( Element parent, String localName ) {
    // use the same prefix as the parent node to avoid modifying
    // the namespace binding.
    String qname = parent.getTagName();
    int idx = qname.indexOf(':');
    if(idx==-1)     qname = localName;
    else            qname = qname.substring(0,idx+1)+localName;

    Element child = parent.getOwnerDocument().createElementNS( WellKnownNamespace.XML_SCHEMA, qname );

    NodeList children = parent.getChildNodes();

    if( children.getLength()==0 )
        parent.appendChild(child);
    else
        parent.insertBefore( child, children.item(0) );

    return child;
}
 
Example 4
Project: springbootWeb   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 6 votes vote down vote up
private void parseIgnoreColumnByRegex(TableConfiguration tc, Node node) {
    Properties attributes = parseAttributes(node);
    String pattern = attributes.getProperty("pattern"); //$NON-NLS-1$

    IgnoredColumnPattern icPattern = new IgnoredColumnPattern(pattern);

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("except".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseException(icPattern, childNode);
        }
    }

    tc.addIgnoredColumnPattern(icPattern);
}
 
Example 5
Project: cuttlefish   File: XMLUtil.java   Source Code and License 6 votes vote down vote up
static public Hashtable<String, String> getArguments(Node source) {
	Hashtable<String, String> argumentTable = new Hashtable<String, String>();
	NodeList arguments = source.getChildNodes();
      	      
      	   
            for( int i=0; i<arguments.getLength(); i++ ){
         	   	  
          	  Node argument = arguments.item(i);
         	   	  if(argument.getNodeName().equals("Argument")){
          	 
              	  String name = argument.getAttributes().getNamedItem("name").getNodeValue();
             	   	  String value = argument.getTextContent();
             	      System.out.println(name + "->" + value);
             	   	  argumentTable.put(name, value);
         	   	  }
         	   	 
            }
	return argumentTable;
}
 
Example 6
Project: incubator-netbeans   File: M2AuxilaryConfigImpl.java   Source Code and License 6 votes vote down vote up
static void findDuplicateElements(@NonNull Element parent, @NonNull ProblemProvider pp, FileObject config) {
    NodeList l = parent.getChildNodes();
    int nodeCount = l.getLength();
    Set<String> known = new HashSet<String>();
    for (int i = 0; i < nodeCount; i++) {
        if (l.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Node node = l.item(i);
            String localName = node.getLocalName();
            localName = localName == null ? node.getNodeName() : localName;
            String id = localName + "|" + node.getNamespaceURI();
            if (!known.add(id)) {
                //we have a duplicate;
                pp.setProblem(ProjectProblem.createWarning(
                                TXT_Problem_Broken_Config2(), 
                                DESC_Problem_Broken_Config2(), 
                                new ProblemReporterImpl.MavenProblemResolver(ProblemReporterImpl.createOpenFileAction(config), BROKEN_NBCONFIG)));
            }
        }
    }
}
 
Example 7
Project: TextHIN   File: PopularityCache.java   Source Code and License 6 votes vote down vote up
public static Map<String, Integer> extractMapValue(NodeList results) {
	Map<String, Integer> map = new HashMap<String, Integer>();
	for (int i = 0; i < results.getLength(); i++) {
		NodeList bindings = ((Element) results.item(i)).getElementsByTagName("binding");
		String property = null;
		int count = 0;
		for (int j = 0; j < bindings.getLength(); j++) {
			Element binding = (Element) bindings.item(j);
			String var = binding.getAttribute("name");
			if (var.equals("p") || var.equals("type")) {
				String uri = SparqlExecutor.getTagValue("uri", binding);
				property = FreebaseInfo.uri2id(uri);
			}
			if (var.equals("count")) {
				count = Integer.parseInt(SparqlExecutor.getTagValue("literal", binding));
			}
		}
		map.put(property, count);
	}
	return map;
}
 
Example 8
Project: jspider   File: FieldDefineBeanDefinitionParser.java   Source Code and License 6 votes vote down vote up
private void parseFieldDefines(FieldDefine fieldDefine, Element defineElement) {
    NodeList nodeList = defineElement.getChildNodes();
    if (nodeList != null && nodeList.getLength() > 0) {
        int length = nodeList.getLength();
        List<FieldDefine> list = new LinkedList<FieldDefine>();
        for (int i = 0; i < length; i++) {
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;
                if ("selector".equals(element.getLocalName())) {
                    fieldDefine.setSelector(element.getTextContent());
                } else if ("processor".equals(element.getLocalName())) {
                    fieldDefine.setProcessor(getFieldProcessor(element));
                } else {
                    list.add(parseFieldDefine(element));
                }
            }
        }

        if (list.size() > 0) {
            fieldDefine.setDefines(list.toArray(new FieldDefine[list.size()]));
        }
    }
}
 
Example 9
Project: brModelo   File: PreTextoApenso.java   Source Code and License 6 votes vote down vote up
@Override
protected void ToXmlValores(Document doc, Element me) {
    super.ToXmlValores(doc, me);

    me.appendChild(util.XMLGenerate.ValorInteger(doc, "Alinhamento", getAlinhamento().ordinal()));
    me.appendChild(util.XMLGenerate.ValorBoolean(doc, "CentrarVertical", isCentrarVertical()));
    me.appendChild(util.XMLGenerate.ValorInteger(doc, "Tipo", getTipo().ordinal()));
    me.appendChild(util.XMLGenerate.ValorBoolean(doc, "Autosize", isAutosize()));
    me.appendChild(util.XMLGenerate.ValorBoolean(doc, "MovimentacaoManual", isMovimentacaoManual()));

    //remover dicionĂ¡rio do XML do objeto.
    NodeList nl = me.getElementsByTagName("Dicionario");
    if (nl != null && nl.getLength() > 0) {
        me.removeChild(nl.item(0));
    }

}
 
Example 10
Project: hadoop   File: TestHsWebServicesTasks.java   Source Code and License 6 votes vote down vote up
@Test
public void testTasksXML() throws JSONException, Exception {

  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList tasks = dom.getElementsByTagName("tasks");
    assertEquals("incorrect number of elements", 1, tasks.getLength());
    NodeList task = dom.getElementsByTagName("task");
    verifyHsTaskXML(task, jobsMap.get(id));
  }
}
 
Example 11
Project: org.mybatis.generator.core-1.3.5   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 6 votes vote down vote up
public Configuration parseConfiguration(Element rootNode)
        throws XMLParserException {

    Configuration configuration = new Configuration();

    NodeList nodeList = rootNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("properties".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperties(configuration, childNode);
        } else if ("classPathEntry".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseClassPathEntry(configuration, childNode);
        } else if ("context".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseContext(configuration, childNode);
        }
    }

    return configuration;
}
 
Example 12
Project: Tarski   File: XMLDOMHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Return the text that a node contains. This routine:
 * <ul>
 * <li>Ignores comments and processing instructions.
 * <li>Concatenates TEXT nodes, CDATA nodes, and the results of recursively processing EntityRef
 * nodes.
 * <li>Ignores any element nodes in the sublist. (Other possible options are to recurse into
 * element sublists or throw an exception.)
 * </ul>
 * 
 * @param node a DOM node
 * @return a String representing its contents
 */
public static String getText(Node node) {
  StringBuffer result = new StringBuffer();
  if (!node.hasChildNodes())
    return "";

  NodeList list = node.getChildNodes();
  for (int i = 0; i < list.getLength(); i++) {
    Node subnode = list.item(i);
    if (subnode.getNodeType() == Node.TEXT_NODE) {
      result.append(subnode.getNodeValue());
    } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) {
      result.append(subnode.getNodeValue());
    } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
      // Recurse into the subtree for text
      // (and ignore comments)
      result.append(getText(subnode));
    }
  }

  return result.toString();
}
 
Example 13
Project: OpenJSharp   File: SAXImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Create an org.w3c.dom.NodeList from a node in the tree
 */
public NodeList makeNodeList(int index) {
    if (_nodeLists == null) {
        _nodeLists = new NodeList[_namesSize];
    }

    int nodeID = makeNodeIdentity(index);
    if (nodeID < 0) {
        return null;
    }
    else if (nodeID < _nodeLists.length) {
        return (_nodeLists[nodeID] != null) ? _nodeLists[nodeID]
               : (_nodeLists[nodeID] = new DTMAxisIterNodeList(this,
                                             new SingletonIterator(index)));
}
    else {
        return new DTMAxisIterNodeList(this, new SingletonIterator(index));
    }
}
 
Example 14
Project: TuLiPA-frames   File: XMLLemmaReader.java   Source Code and License 6 votes vote down vote up
public static List<CoAnchor> getCoAnchors(Element e) {
    List<CoAnchor> coancs = new LinkedList<CoAnchor>();
    NodeList l = e.getChildNodes();

    for (int i = 0; i < l.getLength(); i++) {
        Node n = l.item(i);

        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) n;
            if (el.getTagName().equals("coanchor")) {
                String nid = el.getAttribute("node_id");
                CoAnchor coanc = new CoAnchor(nid);
                coanc.setLex(getLex(el));
                String cat = el.getAttribute("cat");
                coanc.setCat(cat);
                coancs.add(coanc);
            }
        }
    }
    return coancs;
}
 
Example 15
Project: openjdk-jdk10   File: ExsltMath.java   Source Code and License 6 votes vote down vote up
/**
 * The math:highest function returns the nodes in the node set whose value is the maximum
 * value for the node set. The maximum value for the node set is the same as the value as
 * calculated by math:max. A node has this maximum value if the result of converting its
 * string value to a number as if by the number function is equal to the maximum value,
 * where the equality comparison is defined as a numerical comparison using the = operator.
 * <p>
 * If any of the nodes in the node set has a non-numeric value, the math:max function will
 * return NaN. The definition numeric comparisons entails that NaN != NaN. Therefore if any
 * of the nodes in the node set has a non-numeric value, math:highest will return an empty
 * node set.
 *
 * @param nl The NodeList for the node-set to be evaluated.
 *
 * @return node-set with nodes containing the maximum value found, an empty node-set
 * if any node cannot be converted to a number.
 */
public static NodeList highest (NodeList nl)
{
  double maxValue = max(nl);

  NodeSet highNodes = new NodeSet();
  highNodes.setShouldCacheNodes(true);

  if (Double.isNaN(maxValue))
    return highNodes;  // empty Nodeset

  for (int i = 0; i < nl.getLength(); i++)
  {
    Node n = nl.item(i);
    double d = toNumber(n);
    if (d == maxValue)
      highNodes.addElement(n);
  }
  return highNodes;
}
 
Example 16
Project: kaltura-ce-sakai-extension   File: KalturaSwfFlavorParamsOutput.java   Source Code and License 6 votes vote down vote up
public KalturaSwfFlavorParamsOutput(Element node) throws KalturaApiException {
    super(node);
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("flashVersion")) {
            this.flashVersion = ParseUtils.parseInt(txt);
            continue;
        } else if (nodeName.equals("poly2Bitmap")) {
            this.poly2Bitmap = ParseUtils.parseBool(txt);
            continue;
        } 
    }
}
 
Example 17
Project: MybatisGeneatorUtil   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 6 votes vote down vote up
protected void parseConnectionFactory(Context context, Node node) {
    ConnectionFactoryConfiguration connectionFactoryConfiguration = new ConnectionFactoryConfiguration();

    context.setConnectionFactoryConfiguration(connectionFactoryConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type"); //$NON-NLS-1$

    if (stringHasValue(type)) {
        connectionFactoryConfiguration.setConfigurationType(type);
    }

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(connectionFactoryConfiguration, childNode);
        }
    }
}
 
Example 18
Project: server-utility   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 6 votes vote down vote up
protected void parseSqlMapGenerator(Context context, Node node) {
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();

    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

    Properties attributes = parseAttributes(node);
    String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
    String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$

    sqlMapGeneratorConfiguration.setTargetPackage(targetPackage);
    sqlMapGeneratorConfiguration.setTargetProject(targetProject);

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(sqlMapGeneratorConfiguration, childNode);
        }
    }
}
 
Example 19
Project: pmTrans   File: EditingPane.java   Source Code and License 6 votes vote down vote up
public void loadTranscription(File transcriptionFile)
		throws ParserConfigurationException, SAXException, IOException {
	text.setText("");

	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(transcriptionFile);

	// Text
	text.setText(doc.getElementsByTagName("text").item(0).getTextContent());

	// Timestamps
	NodeList nList = doc.getElementsByTagName("timeStamp");
	for (int temp = 0; temp < nList.getLength(); temp++) {
		Element timestamp = (Element) nList.item(temp);
		printTimestamp(Integer.parseInt(timestamp.getAttribute("start")),
				Integer.parseInt(timestamp.getAttribute("lenght")));
	}

	changed = false;
}
 
Example 20
Project: parabuild-ci   File: DwrXmlConfigurator.java   Source Code and License 6 votes vote down vote up
/**
 * Internal method to load the create/convert elements
 * @param child The element to read
 */
private void loadAllows(Element child)
{
    NodeList allows = child.getChildNodes();
    for (int j = 0; j < allows.getLength(); j++)
    {
        if (allows.item(j).getNodeType() == Node.ELEMENT_NODE)
        {
            Element allower = (Element) allows.item(j);

            if (allower.getNodeName().equals(ELEMENT_CREATE))
            {
                loadCreate(allower);
            }
            else if (allower.getNodeName().equals(ELEMENT_CONVERT))
            {
                loadConvert(allower);
            }
            else if (allower.getNodeName().equals(ELEMENT_FILTER))
            {
                loadFilter(allower);
            }
        }
    }
}
 
Example 21
Project: hadoop   File: TestRMWebServicesApps.java   Source Code and License 6 votes vote down vote up
@Test
public void testSingleAppsXML() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  RMApp app1 = rm.submitApp(CONTAINER_MB, "testwordcount", "user1");
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").path(app1.getApplicationId().toString())
      .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("app");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyAppsXML(nodes, app1);
  rm.stop();
}
 
Example 22
Project: summer-mybatis-generator   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 6 votes vote down vote up
protected void parseSqlMapGenerator(Context context, Node node) {
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();

    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

    Properties attributes = parseAttributes(node);
    String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
    String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$

    sqlMapGeneratorConfiguration.setTargetPackage(targetPackage);
    sqlMapGeneratorConfiguration.setTargetProject(targetProject);

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(sqlMapGeneratorConfiguration, childNode);
        }
    }
}
 
Example 23
Project: oscm   File: SharesCalculatorBeanCutOffDayIT.java   Source Code and License 6 votes vote down vote up
private void verify_SupplierResult_Service(Document xml,
        Organization resaleOrg, OfferingType type, String roleString)
        throws XPathExpressionException {

    NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
            + roleString
            + "RevenueShareResult/Currency/Marketplace/Service");

    for (int i = 0; i < services.getLength(); i++) {
        String model = XMLConverter.getStringAttValue(services.item(i),
                "model");

        if (type.name().equals(model)) {

            verify_SupplierResult_RevenueShareDetails(services.item(i));
            if (resaleOrg != null) {
                verify_ResaleOrganization(services.item(i), resaleOrg);
            }

        }
    }
}
 
Example 24
Project: DocIT   File: Cut.java   Source Code and License 6 votes vote down vote up
public static void cut(Document doc) {
 	    
    // Get the matching elements
    NodeList nodelist = doc.getElementsByTagName("salary");
    		    
    // Process the elements in the nodelist
    for (int i=0; i<nodelist.getLength(); i++) {
    	
        // Get element
        Element elem = (Element)nodelist.item(i);
        
        // Transform content of element
        double value = parseDouble(elem.getTextContent());
        elem.setTextContent(Double.toString(value / 2));
        
    }
}
 
Example 25
Project: ChronoBike   File: ActionShowScreen.java   Source Code and License 6 votes vote down vote up
private void setEditTagsForName(Document docOutput, String csName) 
{
	NodeList lst = docOutput.getElementsByTagName(csName) ;
	int nb = lst.getLength() ;
	for (int i=0; i<nb; i++)
	{
		Element e = (Element)lst.item(i) ;
		if (e.hasAttribute("linkedvalue"))
		{
			String value = e.getAttribute("value");
			if (value != null && value.equals(""))
			{
				String protection = e.getAttribute("protection");
				if (protection == null || protection.equals("") || protection.equals("autoskip"))
				{
					String length = e.getAttribute("length");
					int nLength = 1;
					if (length != null && !length.equals("")) {
						nLength = new Integer(length).intValue();
					}
					e.setAttribute("value", StringUtil.rightPad("", nLength, '*'));
				}				
			}
		}
	}
}
 
Example 26
Project: kaltura-ce-sakai-extension   File: KalturaSshImportJobData.java   Source Code and License 6 votes vote down vote up
public KalturaSshImportJobData(Element node) throws KalturaApiException {
    super(node);
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("privateKey")) {
            this.privateKey = ParseUtils.parseString(txt);
            continue;
        } else if (nodeName.equals("publicKey")) {
            this.publicKey = ParseUtils.parseString(txt);
            continue;
        } else if (nodeName.equals("passPhrase")) {
            this.passPhrase = ParseUtils.parseString(txt);
            continue;
        } 
    }
}
 
Example 27
Project: incubator-netbeans   File: XMLSyntaxParserTest.java   Source Code and License 6 votes vote down vote up
public void testParsePI() throws Exception {
    BaseDocument basedoc = getDocument("resources/PI_after_prolog.xml");
    XMLSyntaxParser parser = new XMLSyntaxParser();

    Document doc = parser.parse(basedoc);            
    List<Token> tokens = doc.getTokens();
    assertEquals(12, tokens.size());
    assertEquals(TokenType.TOKEN_PI_START_TAG, tokens.get(0).getType());
    assertEquals(TokenType.TOKEN_PI_END_TAG, tokens.get(4).getType());
    assertEquals(TokenType.TOKEN_PI_START_TAG, tokens.get(6).getType());
    assertEquals(TokenType.TOKEN_PI_NAME, tokens.get(7).getType());
    assertEquals("Siebel-Property-Set", tokens.get(7).getValue());
    assertEquals(TokenType.TOKEN_PI_VAL, tokens.get(9).getType());
    NodeList nl = doc.getChildNodes();
    assertEquals(2, nl.getLength());    
}
 
Example 28
Project: incubator-netbeans   File: XMLUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Find all direct child elements of an element.
 * More useful than {@link Element#getElementsByTagNameNS} because it does
 * not recurse into recursive child elements.
 * Children which are all-whitespace text nodes or comments are ignored; others cause
 * an exception to be thrown.
 * @param parent a parent element in a DOM tree
 * @return a list of direct child elements (may be empty)
 * @throws IllegalArgumentException if there are non-element children besides whitespace
 */
static List<Element> findSubElements(Element parent) throws IllegalArgumentException {
    NodeList l = parent.getChildNodes();
    List<Element> elements = new ArrayList<>(l.getLength());
    for (int i = 0; i < l.getLength(); i++) {
        Node n = l.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            elements.add((Element)n);
        } else if (n.getNodeType() == Node.TEXT_NODE) {
            String text = ((Text)n).getNodeValue();
            if (text.trim().length() > 0) {
                throw new IllegalArgumentException("non-ws text encountered in " + parent + ": " + text); // NOI18N
            }
        } else if (n.getNodeType() == Node.COMMENT_NODE) {
            // OK, ignore
        } else {
            throw new IllegalArgumentException("unexpected non-element child of " + parent + ": " + n); // NOI18N
        }
    }
    return elements;
}
 
Example 29
Project: winter   File: XMLMatchableReader.java   Source Code and License 5 votes vote down vote up
/**
 * returns a list of values from a child node of the first parameter. The
 * list values are expected to be atomic, i.e. no complex node structures
 * 
 * @param node
 *            the node containing the data
 * @param childName
 *            the name of the child node
 * @return a list of values from the specified child node
 */
protected List<String> getListFromChildElement(Node node, String childName) {

	// get all child nodes
	NodeList children = node.getChildNodes();

	// iterate over the child nodes until the node with childName is found
	for (int j = 0; j < children.getLength(); j++) {
		Node child = children.item(j);

		// check the node type and name
		if (child.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
				&& child.getNodeName().equals(childName)) {

			// prepare a list to hold all values
			List<String> values = new ArrayList<>(child.getChildNodes()
					.getLength());

			// iterate the value nodes
			for (int i = 0; i < child.getChildNodes().getLength(); i++) {
				Node valueNode = child.getChildNodes().item(i);
				String value = valueNode.getTextContent().trim();

				// add the value
				values.add(value);
			}

			return values;
		}
	}

	return null;
}
 
Example 30
Project: incubator-netbeans   File: Document.java   Source Code and License 5 votes vote down vote up
/**
 * This is a convenience attribute that allows direct access to the child 
 * node that is the document element of the document.
 */
public org.w3c.dom.Element getDocumentElement() {
    if(hasChildNodes()) {
        NodeList childNodes = getChildNodes();
        for (int i=0;i<childNodes.getLength(); i++) {
            Node child = (Node)childNodes.item(i);
            if (child instanceof org.w3c.dom.Element)
                return (org.w3c.dom.Element)child;
        }
    }
    return null;
}
 
Example 31
Project: OpenJSharp   File: WSDLInternalizationLogic.java   Source Code and License 5 votes vote down vote up
private Element insertJAXWSBindingsElement( Element parent, String localName ) {
    String qname = "JAXWS:"+localName;

    Element child = parent.getOwnerDocument().createElementNS(JAXWSBindingsConstants.NS_JAXWS_BINDINGS, qname );

    NodeList children = parent.getChildNodes();

    if( children.getLength()==0 )
        parent.appendChild(child);
    else
        parent.insertBefore( child, children.item(0) );

    return child;
}
 
Example 32
Project: convertigo-engine   File: WebClipper.java   Source Code and License 5 votes vote down vote up
protected void generateIds(Element original, Element copy) {
	String attr = context.getIdToXpathManager().addNode(original);
	
	Engine.logBeans.trace("Added node : "  + original.getNodeName() + " with id :" + attr);
	copy.setAttribute("twsid", attr);
	
	NodeList original_nodes = original.getChildNodes();
	NodeList copy_nodes = copy.getChildNodes();
	for (int i = 0; i < original_nodes.getLength(); i++) {
		Node node = original_nodes.item(i);
		Node copy_node = copy_nodes.item(i);
		if (node instanceof Element && copy_node instanceof Element) {
			generateIds((Element)node, (Element)copy_node);
		}
	}
}
 
Example 33
Project: convertigo-engine   File: Transaction.java   Source Code and License 5 votes vote down vote up
@Override
protected String getWsdlBackupDir(Element element) throws Exception {
	String backupDir = super.getWsdlBackupDir(element);
	
	Element connectorNode = (Element) element.getParentNode();
   	NodeList properties = connectorNode.getElementsByTagName("property");
	Element pName = (Element) XMLUtils.findNodeByAttributeValue(properties, "name", "name");
	String connectorName = (String) XMLUtils.readObjectFromXml((Element) XMLUtils.findChildNode(pName, Node.ELEMENT_NODE));
	backupDir += "/" + connectorName;
	return backupDir;
}
 
Example 34
Project: geomapapp   File: LayerSetDetails.java   Source Code and License 5 votes vote down vote up
private static List getElements(Node node, String elementName) {
	List list = new LinkedList();
	NodeList nodeList = node.getChildNodes();
	for (int i = 0; i < nodeList.getLength(); i++) {
		if (nodeList.item(i).getNodeName().equals(elementName)
				&& nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
			list.add(nodeList.item(i));
		}
	}

	return list;
}
 
Example 35
Project: mi-firma-android   File: InitiativesList.java   Source Code and License 5 votes vote down vote up
/** Recupera el &iacute;ndice del siguiente nodo de la lista de tipo
 * <code>Element</code>. Empieza a comprobar los nodos a partir del
 * &iacute;ndice marcado. Si no encuentra un nodo de tipo <i>elemento</i>
 * devuelve -1.
 * @param nodes Listado de nodos.
 * @param currentIndex &Iacute;ndice del listado a partir del cual se empieza la
 *                     comprobaci&oacute;n.
 * @return &Iacute;ndice del siguiente node de tipo Element o -1 si no se
 *         encontr&oacute;. */
private static int nextNodeElementIndex(final NodeList nodes, final int currentIndex) {
    Node node;
    int i = currentIndex;
    while (i < nodes.getLength()) {
        node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            return i;
        }
        i++;
    }
    return -1;
}
 
Example 36
Project: Proyecto-DASI   File: ReadXMLTestSequence.java   Source Code and License 5 votes vote down vote up
private String getVictimArrivalTimeValueString(Element info, String tag){
NodeList timeNmElmntLst = info.getElementsByTagName(tag);
Element timeNmElmnt = (Element) timeNmElmntLst.item(0);
NodeList timeNm = timeNmElmnt.getChildNodes();					  
String valuetime = ((Node)timeNm.item(0)).getNodeValue();					  
return valuetime;
}
 
Example 37
Project: openjdk-jdk10   File: GeneratorBase.java   Source Code and License 5 votes vote down vote up
protected void writeHandlerConfig(String className, JDefinedClass cls, WsimportOptions options) {
    Element e = options.getHandlerChainConfiguration();
    if (e == null) {
        return;
    }
    JAnnotationUse handlerChainAnn = cls.annotate(cm.ref(HandlerChain.class));
    NodeList nl = e.getElementsByTagNameNS(
        "http://java.sun.com/xml/ns/javaee", "handler-chain");
    if(nl.getLength() > 0){
        String fName = getHandlerConfigFileName(className);
        handlerChainAnn.param("file", fName);
        generateHandlerChainFile(e, className);
    }
}
 
Example 38
Project: jspider   File: FieldDefineBeanDefinitionParser.java   Source Code and License 5 votes vote down vote up
private Object[] getFieldProcessorArguments(Element element) {
    NodeList nodeList = element.getChildNodes();
    List<Object> list = new LinkedList<Object>();
    if (nodeList != null && nodeList.getLength() > 0) {
        int length = nodeList.getLength();
        for (int i = 0; i < length; i++) {
            list.add(nodeList.item(i).getTextContent());
        }
    }
    return list.toArray(new Object[list.size()]);
}
 
Example 39
Project: Proyecto-DASI   File: ReadXMLTestRobots.java   Source Code and License 5 votes vote down vote up
public synchronized int getRobotInitialEnergy(Element info, String tag){
NodeList initialenergyNmElmntLst = info.getElementsByTagName(tag);
Element initialenergyNmElmnt = (Element) initialenergyNmElmntLst.item(0);
NodeList initialenergyNm = initialenergyNmElmnt.getChildNodes();					  
String initialenergy = ((Node)initialenergyNm.item(0)).getNodeValue();					  
return Integer.parseInt(initialenergy);
}
 
Example 40
Project: nifi-registry   File: AbstractPolicyBasedAuthorizer.java   Source Code and License 5 votes vote down vote up
private Group parseGroup(final Element element) {
    final Group.Builder builder = new Group.Builder()
            .identifier(element.getAttribute(IDENTIFIER_ATTR))
            .name(element.getAttribute(NAME_ATTR));

    NodeList groupUsers = element.getElementsByTagName(GROUP_USER_ELEMENT);
    for (int i=0; i < groupUsers.getLength(); i++) {
        Element groupUserNode = (Element) groupUsers.item(i);
        builder.addUser(groupUserNode.getAttribute(IDENTIFIER_ATTR));
    }

    return builder.build();
}
 
Example 41
Project: ccpa   File: TreeTransformer.java   Source Code and License 5 votes vote down vote up
private static int getMaxRequiredRegistersInNode(Node node)
{
	int max = 0;
	if (!node.getNodeName().equals("op"))
		return 0;

	NamedNodeMap attr = node.getAttributes();
	String operation = attr.getNamedItem("name").getTextContent();
	NodeList children = node.getChildNodes();

	if (operation.equals(";") || operation.equals("if") || operation.equals("while") || operation.equals("doWhile"))
	{
		return Math.max(getMaxRequiredRegistersInNode(children.item(0)),
				        getMaxRequiredRegistersInNode(children.item(1)));
	}
	else if (operation.equals("if/else") || operation.equals("for"))
	{
		return Math.max(Math.max(getMaxRequiredRegistersInNode(children.item(0)),
				        getMaxRequiredRegistersInNode(children.item(1))),
				        getMaxRequiredRegistersInNode(children.item(2)));
	}
	else
	{
		for (int i = 0; i < children.getLength(); i++)
		{
			max = Math.max(max, getMaxRequiredRegistersInNode(children.item(i)));
		}
		return max + 1;
	}
}
 
Example 42
Project: kaltura-ce-sakai-extension   File: KalturaBulkUploadPluginData.java   Source Code and License 5 votes vote down vote up
public KalturaBulkUploadPluginData(Element node) throws KalturaApiException {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("field")) {
            this.field = ParseUtils.parseString(txt);
            continue;
        } else if (nodeName.equals("value")) {
            this.value = ParseUtils.parseString(txt);
            continue;
        } 
    }
}
 
Example 43
Project: kaltura-ce-sakai-extension   File: KalturaPartnerUsage.java   Source Code and License 5 votes vote down vote up
public KalturaPartnerUsage(Element node) throws KalturaApiException {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("hostingGB")) {
            this.hostingGB = ParseUtils.parseFloat(txt);
            continue;
        } else if (nodeName.equals("Percent")) {
            this.Percent = ParseUtils.parseFloat(txt);
            continue;
        } else if (nodeName.equals("packageBW")) {
            this.packageBW = ParseUtils.parseInt(txt);
            continue;
        } else if (nodeName.equals("usageGB")) {
            this.usageGB = ParseUtils.parseFloat(txt);
            continue;
        } else if (nodeName.equals("reachedLimitDate")) {
            this.reachedLimitDate = ParseUtils.parseInt(txt);
            continue;
        } else if (nodeName.equals("usageGraph")) {
            this.usageGraph = ParseUtils.parseString(txt);
            continue;
        } 
    }
}
 
Example 44
Project: oscm   File: MigrationBillingResultGatheredEvents.java   Source Code and License 5 votes vote down vote up
private Element createNodeTotalEventCosts(Node gatheredEvents) {
    PriceConverter priceFormatConverter = new PriceConverter();
    BigDecimal totalCosts = BigDecimal.ZERO;
    NodeList childNodes = gatheredEvents.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        if ("Event".equals(childNodes.item(i).getNodeName())) {
            Node costNode = XMLConverter.getLastChildNode(childNodes.item(i),
                    BillingResultXMLTags.COST_FOR_EVENT_TYPE_NODE_NAME);
            BigDecimal amount = XMLConverter.getBigDecimalAttValue(
                    costNode, BillingResultXMLTags.AMOUNT_ATTRIBUTE_NAME);
            totalCosts = totalCosts.add(amount);
        }
    }

    Element gatheredEventsCostElement = XMLConverter.newElement(
            BillingResultXMLTags.GATHERED_EVENTS_COSTS_NODE_NAME,
            (Element) gatheredEvents);

    // round total costs before setting the attribute value
    totalCosts = totalCosts.setScale(
            PriceConverter.NORMALIZED_PRICE_SCALING, RoundingMode.HALF_UP);
    gatheredEventsCostElement.setAttribute(
            BillingResultXMLTags.AMOUNT_ATTRIBUTE_NAME,
            priceFormatConverter.getValueToDisplay(totalCosts, false));

    return gatheredEventsCostElement;
}
 
Example 45
Project: kaltura-ce-sakai-extension   File: KalturaAttachmentAssetListResponse.java   Source Code and License 5 votes vote down vote up
public KalturaAttachmentAssetListResponse(Element node) throws KalturaApiException {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("objects")) {
            this.objects = ParseUtils.parseArray(KalturaAttachmentAsset.class, aNode);
            continue;
        } else if (nodeName.equals("totalCount")) {
            this.totalCount = ParseUtils.parseInt(txt);
            continue;
        } 
    }
}
 
Example 46
Project: dacapobench   File: RuleSetFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Parse a value node
 * @param valueNode must be a value element node
 * @return the value
 */
private String parseValueNode(Node valueNode) {
    StringBuffer buffer = new StringBuffer();
    NodeList nodeList = valueNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
            buffer.append(node.getNodeValue());
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            buffer.append(node.getNodeValue());
        }
    }
    return buffer.toString();
}
 
Example 47
Project: openjdk-jdk10   File: AuctionController.java   Source Code and License 5 votes vote down vote up
/**
 * Check usage of javax.xml.datatype.Duration class.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testGetItemDuration() throws Exception {
    String xmlFile = XML_DIR + "itemsDuration.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document document = dbf.newDocumentBuilder().parse(xmlFile);

    Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0);

    NodeList childList = durationElement.getChildNodes();

    for (int i = 0; i < childList.getLength(); i++) {
        System.out.println("child " + i + childList.item(i));
    }

    Duration duration = DatatypeFactory.newInstance().newDuration("P365D");
    Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue());
    assertFalse(sellDuration.isShorterThan(duration));
    assertFalse(sellDuration.isLongerThan(duration));
    assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365));
    assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration);

    Duration myDuration = sellDuration.add(duration);
    assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)),
            DatatypeFactory.newInstance().newDuration("P730D"));
}
 
Example 48
Project: dacapobench   File: RuleSetFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Parse a priority node
 * @param rule the rule being constructed
 * @param priorityNode must be a priority element
 */
private void parsePriorityNode(Rule rule, Node priorityNode) {
    StringBuffer buffer = new StringBuffer();
    NodeList nodeList = priorityNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.TEXT_NODE) {
            buffer.append(node.getNodeValue());
        }
    }
    rule.setPriority(new Integer(buffer.toString().trim()).intValue());
}
 
Example 49
Project: hadoop   File: TestAMWebServicesAttempts.java   Source Code and License 5 votes vote down vote up
@Test
public void testTaskAttemptsXML() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      ClientResponse response = r.path("ws").path("v1").path("mapreduce")
          .path("jobs").path(jobId).path("tasks").path(tid).path("attempts")
          .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);

      assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
      String xml = response.getEntity(String.class);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(xml));
      Document dom = db.parse(is);
      NodeList attempts = dom.getElementsByTagName("taskAttempts");
      assertEquals("incorrect number of elements", 1, attempts.getLength());

      NodeList nodes = dom.getElementsByTagName("taskAttempt");
      verifyAMTaskAttemptsXML(nodes, task);
    }
  }
}
 
Example 50
Project: Proyecto-DASI   File: GeneraEstadisticaLlegadaYAsignacionVictimas.java   Source Code and License 5 votes vote down vote up
public static String ObtenerElementoItem(Element info, String tag){
	  NodeList idNmElmntLst = info.getElementsByTagName(tag);
	  Element idNmElmnt = (Element) idNmElmntLst.item(0);
	  NodeList idNm = idNmElmnt.getChildNodes();					  
	  String valor = ((Node)idNm.item(0)).getNodeValue();
	  return valor;				
}
 
Example 51
Project: summer-mybatis-generator   File: MyBatisGeneratorConfigurationParser.java   Source Code and License 5 votes vote down vote up
private void parseJavaClientGenerator(Context context, Node node) {
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();

    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

    Properties attributes = parseAttributes(node);
    String type = attributes.getProperty("type"); //$NON-NLS-1$
    String targetPackage = attributes.getProperty("targetPackage"); //$NON-NLS-1$
    String targetProject = attributes.getProperty("targetProject"); //$NON-NLS-1$
    String implementationPackage = attributes
            .getProperty("implementationPackage"); //$NON-NLS-1$

    javaClientGeneratorConfiguration.setConfigurationType(type);
    javaClientGeneratorConfiguration.setTargetPackage(targetPackage);
    javaClientGeneratorConfiguration.setTargetProject(targetProject);
    javaClientGeneratorConfiguration
            .setImplementationPackage(implementationPackage);

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node childNode = nodeList.item(i);

        if (childNode.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        if ("property".equals(childNode.getNodeName())) { //$NON-NLS-1$
            parseProperty(javaClientGeneratorConfiguration, childNode);
        }
    }
}
 
Example 52
Project: Proyecto-DASI   File: ReadXMLTestRobots.java   Source Code and License 5 votes vote down vote up
private synchronized String getRobotCoordinateX(Element info, String tagcoordinate, String tagdimension){
      String valuex = "";          
NodeList coordinateNmElmntLst = info.getElementsByTagName(tagcoordinate);
Node coordinateNode = coordinateNmElmntLst.item(0);
if (coordinateNode.getNodeType() == Node.ELEMENT_NODE){
 Element coorInfo = (Element) coordinateNode;			  
 //Obtain information about x coordinate for the current robot 
 NodeList xNmElmntLst = coorInfo.getElementsByTagName(tagdimension);
 Element xNmElmnt = (Element) xNmElmntLst.item(0);
 NodeList xNm = xNmElmnt.getChildNodes();					  
 valuex = ((Node)xNm.item(0)).getNodeValue();				  
}
return valuex;
}
 
Example 53
Project: OperatieBRP   File: DomUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Geef het eerste kind element met de gegeven naam.
 * @param element element waarin het kind gevonden moet worden
 * @param name naam
 * @return kind indien gevonden, anders null
 */
public static Element getChildElement(final Element element, final String name) {
    final NodeList nodeList = element.getChildNodes();

    for (int index = 0; index < nodeList.getLength(); index++) {
        final Node node = nodeList.item(index);

        if (node instanceof Element && name.equals(node.getLocalName())) {
            return (Element) node;
        }
    }
    return null;
}
 
Example 54
Project: defense-solutions-proofs-of-concept   File: CoTAdapterInbound.java   Source Code and License 5 votes vote down vote up
private NodeList unpackXML(String xml, String targetTag) throws Exception {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		InputSource source = new InputSource();
		source.setCharacterStream(new StringReader(xml));
		Document doc = db.parse(source);
		NodeList nodeList = doc.getElementsByTagName(targetTag);
		return nodeList;
	} catch (Exception e) {
		log.error(e);
		log.error(e.getStackTrace());
		throw (e);
	}
}
 
Example 55
Project: kaltura-ce-sakai-extension   File: KalturaFilterPager.java   Source Code and License 5 votes vote down vote up
public KalturaFilterPager(Element node) throws KalturaApiException {
    NodeList childNodes = node.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node aNode = childNodes.item(i);
        String nodeName = aNode.getNodeName();
        String txt = aNode.getTextContent();
        if (nodeName.equals("pageSize")) {
            this.pageSize = ParseUtils.parseInt(txt);
            continue;
        } else if (nodeName.equals("pageIndex")) {
            this.pageIndex = ParseUtils.parseInt(txt);
            continue;
        } 
    }
}
 
Example 56
Project: incubator-netbeans   File: CatalogFileWrapperDOMImpl.java   Source Code and License 5 votes vote down vote up
private List<CatalogEntry> getEntriesByTagName(CatalogElement tagName,
        CatalogAttribute mappingEntityKey, CatalogAttribute mappedEntityKey){
    bootstrap();
    Object [] obj = {
        tagName.toString(), mappingEntityKey.toString(),
        mappedEntityKey.toString()
    };
    logger.entering("CatalogModelWrapperDOMImpl","getEntriesByTagName", obj);
    
    NodeList nl = catalog.getElementsByTagName(tagName.toString());
    int len = nl.getLength();
    if(len < 1)
        return null;
    List<CatalogEntry> result = new ArrayList<CatalogEntry> (nl.getLength());
    for(int i=0; i<len;i++){
        String mappingEntity = "";
        String mappedEntity = "";
        Element elm = (Element) nl.item(i);
        mappingEntity = elm.getAttribute(mappingEntityKey.toString());
        mappedEntity = elm.getAttribute(mappedEntityKey.toString());
        String strArry[] = {mappingEntityKey.toString(),mappedEntityKey.toString()};
        HashMap<String,String> extraAttrs = getOtherAttributes(elm, strArry);
        CatalogEntry catEnt;
        if(extraAttrs != null)
            catEnt = new CatalogEntryImpl(tagName, mappingEntity, mappedEntity, extraAttrs);
        else
            catEnt = new CatalogEntryImpl(tagName, mappingEntity, mappedEntity);
        result.add(catEnt);
    }
    logger.exiting("CatalogModelWrapperDOMImpl","getEntriesByTagName", result);
    tearDown();
    return result;
}
 
Example 57
Project: cdp4j   File: Crawler.java   Source Code and License 5 votes vote down vote up
public List<String> parse(String content) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new ByteArrayInputStream(content.getBytes()));
    NodeList nodes = document.getElementsByTagName("loc");
    List<String> urls = new ArrayList<>();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String tc = node.getTextContent();
        if ( tc != null ) {
            urls.add(tc);
        }
    }
    return urls;
}
 
Example 58
Project: OpenJSharp   File: AdaptiveResultTreeImpl.java   Source Code and License 5 votes vote down vote up
public NodeList makeNodeList(DTMAxisIterator iter)
{
    if (_dom != null) {
        return _dom.makeNodeList(iter);
    }
    else {
        return super.makeNodeList(iter);
    }
}
 
Example 59
Project: lams   File: UpdateApplicationXmlTask.java   Source Code and License 5 votes vote down vote up
/** Find a matching web element - useful for updating or deleting an existing element */
   protected Element findElementWithModule(Document doc) {
NodeList moduleNodeList = doc.getElementsByTagName("java");
Element matchingModuleElement = findElementWithMatchingText(module, moduleNodeList);
if (matchingModuleElement != null) {
    return (Element) matchingModuleElement.getParentNode();
} else {
    return null;
}
   }
 
Example 60
Project: convertigo-eclipse   File: HtmlConnectorDesignComposite.java   Source Code and License 5 votes vote down vote up
public void changed() {
	getWebViewer().setFocus();
	Thread th = new Thread(new Runnable() {
		
		public void run() {					
			final Document dom = domTreeComp.getCurrentDom();
			Display.getDefault().asyncExec(new Runnable() {
				
				public void run () {
					try {
						String selectedXpath = getWebViewer().getSelectedXpath();

						NodeList nl = getXpathApi().selectNodeList(dom, selectedXpath);
						if (nl.getLength() == 0) {
							boolean bOk = MessageDialog.openConfirm(
									null,
									"Html tree synchronization",
									"The selected element was'nt found in the current HTML tree, would you like to synchronize it with the current HTML page displayed ?"
							);
							if (bOk) {
								// Synchronize the HTML Tree
								domTreeComp.displayXhtml(getWebViewer().getDom());

								// Hightlight the selected item
								selectedXpath = getWebViewer().getSelectedXpath();
							}
						}
						setCurrentAbsoluteXpath(selectedXpath);
						domTreeComp.selectElementInTree(selectedXpath);
					} catch (TransformerException e) {
						ConvertigoPlugin.logException(e, "Xpath not valid");
					}
				}
			});
		}
	});
	th.setName("Document completed Update");
	th.start();
}