Java Code Examples for org.w3c.dom.Node#getTextContent()

The following examples show how to use org.w3c.dom.Node#getTextContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLUtil.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Note: if the content is another element or set of elements, it returns a string representation
 * of the hierarchy.
 */
public static String getTextContent(final Node n) {
   if (n.hasChildNodes()) {
      StringBuffer sb = new StringBuffer();
      NodeList nl = n.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
         sb.append(XMLUtil.elementToString(nl.item(i)));
         if (i < nl.getLength() - 1) {
            sb.append('\n');
         }
      }

      String s = sb.toString();
      if (s.length() != 0) {
         return s;
      }
   }

   return n.getTextContent();
}
 
Example 2
Source File: XMLHelpers.java    From cougar with Apache License 2.0 6 votes vote down vote up
/**
 * Get the Text Content of the first Node in the NodeList that has a matched node name
 *  
 * @param nodeList
 * @param nodeName
 * 
 * @return
 */
public String getTextContentOfNodeFromList(NodeList nodeList, String nodeName) {

	int listLength = nodeList.getLength();
	for (int i=0;i<listLength;i++) {
		Node node = nodeList.item(i);
		if (node.hasChildNodes()) {
			NodeList children = node.getChildNodes();
			int childrenListLength = children.getLength();
			for (int j=0;j<childrenListLength;j++) {
				Node child = children.item(j);
				if (child.getNodeName().equalsIgnoreCase(nodeName.trim())) {
					return child.getTextContent();
				}
			}
		}
	}
	throw new RuntimeException("Unable to find node in list: " + nodeName);
}
 
Example 3
Source File: ManagedRangerAuthorizer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private String parseFingerprint(final String fingerprint) throws AuthorizationAccessException {
    final byte[] fingerprintBytes = fingerprint.getBytes(StandardCharsets.UTF_8);

    try (final ByteArrayInputStream in = new ByteArrayInputStream(fingerprintBytes)) {
        final DocumentBuilder docBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
        final Document document = docBuilder.parse(in);
        final Element rootElement = document.getDocumentElement();

        final NodeList userGroupProviderList = rootElement.getElementsByTagName(USER_GROUP_PROVIDER_ELEMENT);
        if (userGroupProviderList.getLength() != 1) {
            throw new AuthorizationAccessException(String.format("Only one %s element is allowed: %s", USER_GROUP_PROVIDER_ELEMENT, fingerprint));
        }

        final Node userGroupProvider = userGroupProviderList.item(0);
        return userGroupProvider.getTextContent();
    } catch (SAXException | ParserConfigurationException | IOException e) {
        throw new AuthorizationAccessException("Unable to parse fingerprint", e);
    }
}
 
Example 4
Source File: AndroidXMLResourceBundle.java    From Accessibility-Test-Framework-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * For every <string> tag in the given document, adds a property to the given {@link Properties}
 * with the tag's name attribute as the key and the tag's text as the value.
 *
 * @param document a {@link Document} containing android style <string> tags
 * @param properties a {@link Properties} to add strings found in the given {@link Document} to
 */
// dereference of possibly-null reference value
// incompatible types in argument.
@SuppressWarnings({"nullness:dereference.of.nullable", "nullness:argument.type.incompatible"})
private static void addStringsToProperties(Document document, Properties properties) {
  NodeList stringNodes = document.getElementsByTagName(ANDORID_STRING_TAG_NAME);
  for (int i = 0; i < stringNodes.getLength(); i++) {
    Node node = stringNodes.item(i);
    // dereference of possibly-null reference node
    // dereference of possibly-null reference node.getAttributes()
    // dereference of possibly-null reference
    // node.getAttributes().getNamedItem(ANDROID_STRING_NAME_ATTRIBUTE)
    @SuppressWarnings("nullness:dereference.of.nullable")
    String key = node.getAttributes().getNamedItem(ANDROID_STRING_NAME_ATTRIBUTE).getNodeValue();

    String value = node.getTextContent();
    // Android trims whitespace throughout (getTextContent does it internally but not at the ends)
    // so we trim for parity
    value = value.trim();
    // The XML parser does not unescape quotes, so we replace \" with " here for Android parity
    value = value.replace("\\\"", "\"");
    // The XML parser does not unescape quotes, so we replace \' with ' here for Android parity
    value = value.replace("\\'", "'");
    properties.setProperty(key, value);
  }
}
 
Example 5
Source File: FaenorParser.java    From L2jBrasil with GNU General Public License v3.0 6 votes vote down vote up
public static String element(Node parentNode, String elementName, String defaultValue)
{
    try
    {
        NodeList list = parentNode.getChildNodes();
        for (int i=0; i<list.getLength(); i++)
        {
            Node node   = list.item(i);
            if (node.getNodeName().equalsIgnoreCase(elementName))
            {
                return node.getTextContent();
            }
        }
    }
    catch (Exception e)
    {}
    if (defaultValue != null)
        return defaultValue;
    throw new NullPointerException();

}
 
Example 6
Source File: MavenUtils.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private static String getTopLevelValue(Document doc, String parentTagName, String childTagName)
    throws CoreException {
  try {
    NodeList parentElements = doc.getElementsByTagNameNS(POM_XML_NAMESPACE_URI, parentTagName);
    if (parentElements.getLength() > 0) {
      Node parent = parentElements.item(0);
      if (parent.hasChildNodes()) {
        for (int i = 0; i < parent.getChildNodes().getLength(); ++i) {
          Node child = parent.getChildNodes().item(i);
          if (child.getNodeName().equals(childTagName) && (child.getNamespaceURI() == null
              || POM_XML_NAMESPACE_URI.equals(child.getNamespaceURI()))) {
            return child.getTextContent();
          }
        }
      }
    }
    return null;
  } catch (DOMException exception) {
    throw new CoreException(StatusUtil.error(
        MavenUtils.class, "Missing pom.xml element: " + childTagName, exception));
  }
}
 
Example 7
Source File: MavenArtifact.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void parseParentNode(Node node) {
	final NodeList parentNodes = node.getChildNodes();
	String parentGroupId = null;
	String parentArtifactId = null;
	String parentVersion = null;
	for (int k = 0; k < parentNodes.getLength(); k++) {
		final Node childParentNode = parentNodes.item(k);
		final String nodeName = childParentNode.getNodeName();
		if ("groupId".equals(nodeName)) {
			parentGroupId = childParentNode.getTextContent();
		} else if ("artifactId".equals(nodeName)) {
			parentArtifactId = childParentNode.getTextContent();
		} else if ("version".equals(nodeName)) {
			parentVersion = childParentNode.getTextContent();
		}
	}
	if (this.groupId == null) {
		this.groupId = parentGroupId;
	}
	if (this.version == null) {
		this.version = parentVersion;
	}
	this.parent = new MavenArtifact();
	this.parent.groupId = parentGroupId;
	this.parent.artifactId = parentArtifactId;
	this.parent.version = parentVersion;
}
 
Example 8
Source File: DocumentTypeXmlParser.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Parse an element Node containg a single application document status name and return an
 * ApplicationDocumentStatus object for it.
 *
 * @param documentType the document type we are building
 * @param node the status element node
 * @return the ApplicationDocumentStatus constructed
 */
private ApplicationDocumentStatus parseApplicationDocumentStatusHelper(DocumentType documentType, Node node) {
    String statusName = node.getTextContent();
    validateUniqueName(statusName);

    ApplicationDocumentStatus status = new ApplicationDocumentStatus();
    status.setDocumentType(documentType);
    status.getApplicationDocumentStatusId().setDocumentTypeId(documentType.getDocumentTypeId());
    status.setStatusName(statusName);
    // order the statuses according to the order we encounter them
    status.setSequenceNumber(newStatusSequence.nextValue());

    return status;
}
 
Example 9
Source File: GenerateGPX.java    From PocketMaps with MIT License 5 votes vote down vote up
public ArrayList<Location> readGpxFile(File gpxFile) throws IOException, ParserConfigurationException, SAXException, ParseException
{
  ArrayList<Location> posList = new ArrayList<Location>();
  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(gpxFile);
  doc.getDocumentElement().normalize();
  NodeList nList = doc.getElementsByTagName("trkpt");
  for (int i = 0; i < nList.getLength(); i++)
  {
    Node node = nList.item(i);
    System.out.println("Current Element :" + node.getNodeName());
        
    if (node.getNodeType() == Node.ELEMENT_NODE)
    {
      Element element = (Element) node;
      log("--> Tracking-Element: " + element.getTagName());
      log("--> Tracking-Lat: " + element.getAttribute("lat"));
      double lat = Double.parseDouble(element.getAttribute("lat"));
      log("--> Tracking-Lon: " + element.getAttribute("lon"));
      double lon = Double.parseDouble(element.getAttribute("lon"));
      Node eleN = element.getElementsByTagName("ele").item(0);
      log("--> Tracking-ele: " + eleN.getTextContent());
      double ele = Double.parseDouble(eleN.getTextContent());
      Node timeN = element.getElementsByTagName("time").item(0);
      String timeS = timeN.getTextContent();
      log("--> Tracking-time: " + timeS);
      Date timeD = DF.parse(timeS);
      log("--> Tracking-time: " + timeD.getTime());
      Location location = new Location("com.junjunguo.pocketmaps");
      location.setLatitude(lat);
      location.setLongitude(lon);
      location.setAltitude(ele);
      location.setTime(timeD.getTime());
      posList.add(location);
    }
  }
  return posList;
}
 
Example 10
Source File: UserConfig.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void parseXML(Element element) {
	this.user = element.getAttribute("user");
	this.name = element.getAttribute("name");
	this.showName = Boolean.valueOf(element.getAttribute("showName"));
	this.token = element.getAttribute("token");
	this.email = element.getAttribute("email");
	this.hint = element.getAttribute("hint");
	this.website = element.getAttribute("website");
	this.connects = element.getAttribute("connects");
	this.bots = element.getAttribute("bots");
	this.posts = element.getAttribute("posts");
	this.messages = element.getAttribute("messages");
	this.forums = element.getAttribute("forums");
	this.channels = element.getAttribute("channels");
	this.avatars = element.getAttribute("avatars");
	this.scripts = element.getAttribute("scripts");
	this.graphics = element.getAttribute("graphics");
	this.domains = element.getAttribute("domains");
	this.joined = element.getAttribute("joined");
	this.lastConnect = element.getAttribute("lastConnect");
	this.type = element.getAttribute("type");
	this.isFlagged = Boolean.valueOf(element.getAttribute("isFlagged"));
	
	Node node = element.getElementsByTagName("bio").item(0);
	if (node != null) {
		this.bio = node.getTextContent();
	}
	node = element.getElementsByTagName("avatar").item(0);
	if (node != null) {
		this.avatar = node.getTextContent();
	}
	node = element.getElementsByTagName("flaggedReason").item(0);
	if (node != null) {
		this.flaggedReason = node.getTextContent();
	}
}
 
Example 11
Source File: MetsElementVisitor.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the name of title if element is issue
 */
private String getTitle(IMetsElement metsElement) throws MetsExportException {
    if (isIssue(metsElement)) {
        Node partNode = MetsUtils.xPathEvaluateNode(metsElement.getModsStream(), "//*[local-name()='mods']/*[local-name()='titleInfo']/*[local-name()='title']");
        if (partNode == null){
            throw new MetsExportException("Error - missing title. Please insert title.");
        }
        return partNode.getTextContent() + ", ";
    }
    return "";
}
 
Example 12
Source File: Activity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void loadStrings() {
	if (strings != null) {
		return;
	}
	strings = new HashMap<String, String>();
	try {
		URL url = getClass().getResource("/res/values/strings.xml");
		Reader inputReader = new InputStreamReader(url.openStream(), "UTF-8");
		StringWriter output = new StringWriter();
		int next = inputReader.read();
		while (next != -1) {
			output.write(next);
			next = inputReader.read();
		}
		String xml = output.toString();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder parser = factory.newDocumentBuilder();
		StringReader reader = new StringReader(xml);
		InputSource source = new InputSource(reader);
		Document document = parser.parse(source);
		Element root = document.getDocumentElement();

		NodeList children = root.getChildNodes();
		for (int index = 0; index < children.getLength(); index++) {
			Node node = children.item(index);
			if (node instanceof Element) {
				if (node.getNodeName().equals("string")) {
					String key = ((Element)node).getAttribute("name");
					String value = node.getTextContent();
					if (key != null && value != null && !value.isEmpty()) {
						strings.put(key, value);
					}
				}
			}
		}
		
	} catch (Exception exception) {
		log(exception);
	}
}
 
Example 13
Source File: RowLevelSecurity.java    From pentaho-metadata with GNU Lesser General Public License v2.1 5 votes vote down vote up
public RowLevelSecurity( Node rlsNode ) throws Exception {
  String typeString = rlsNode.getAttributes().getNamedItem( ATTR_TYPE ).getTextContent();
  if ( ATTR_VALUE_GLOBAL.equals( typeString ) ) {
    type = Type.GLOBAL;
  } else if ( ATTR_VALUE_ROLE_BASED.equals( typeString ) ) {
    type = Type.ROLEBASED;
  } else {
    type = Type.NONE;
  }
  // global
  Node globalFormulaNode = XMLHandler.getSubNode( rlsNode, ELEM_FORMULA );
  globalConstraint = globalFormulaNode.getTextContent();
  // role-based
  Map<SecurityOwner, String> map = new HashMap<SecurityOwner, String>();
  Node entriesNode = XMLHandler.getSubNode( rlsNode, ELEM_ENTRIES );
  int entryCount = XMLHandler.countNodes( entriesNode, ELEM_ENTRY );
  for ( int i = 0; i < entryCount; i++ ) {
    Node entryNode = XMLHandler.getSubNodeByNr( entriesNode, ELEM_ENTRY, i );
    Node ownerNode = XMLHandler.getSubNode( entryNode, ELEM_OWNER );
    // build owner using its node constructor
    SecurityOwner owner = new SecurityOwner( ownerNode );
    Node formulaNode = XMLHandler.getSubNode( entryNode, ELEM_FORMULA );
    String formula = formulaNode.getTextContent();
    map.put( owner, formula );
  }
  roleBasedConstraintMap = map;

}
 
Example 14
Source File: MapFillComponent.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Float[] getCoords(String address) throws JRException {
	Float[] coords = null;
	if(address != null) {
		try {
			String reqParams = getReqParams();
			reqParams = reqParams != null && reqParams.trim().length() > 0 ? "&" + reqParams : reqParams;
			String urlStr = PLACE_URL_PREFIX + URLEncoder.encode(address, DEFAULT_ENCODING) + reqParams + PLACE_URL_SUFFIX;
			URL url = new URL(urlStr);
			byte[] response = JRLoader.loadBytes(url);
			Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(response));
			Node statusNode = (Node) new DOMXPath(STATUS_NODE).selectSingleNode(document);
			String status = statusNode.getTextContent();
			if(STATUS_OK.equals(status)) {
				coords = new Float[2];
				Node latNode = (Node) new DOMXPath(LATITUDE_NODE).selectSingleNode(document);
				coords[0] = Float.valueOf(latNode.getTextContent());
				Node lngNode = (Node) new DOMXPath(LONGITUDE_NODE).selectSingleNode(document);
				coords[1] = Float.valueOf(lngNode.getTextContent());
			} else {
				throw 
					new JRException(
						EXCEPTION_MESSAGE_KEY_ADDRESS_REQUEST_FAILED,  
						new Object[]{status} 
						);
			}
		} catch (Exception e) {
			throw new JRException(e);
		}
	}
	return coords;
}
 
Example 15
Source File: SdkMavenRepository.java    From bazel with Apache License 2.0 5 votes vote down vote up
static Pom parse(Path path) throws IOException, ParserConfigurationException, SAXException {
  Document pomDocument = null;
  try (InputStream in = path.getInputStream()) {
    pomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
  }
  Node packagingNode = pomDocument.getElementsByTagName("packaging").item(0);
  String packaging = packagingNode == null ? DEFAULT_PACKAGING : packagingNode.getTextContent();
  MavenCoordinate coordinate = MavenCoordinate.create(
      pomDocument.getElementsByTagName("groupId").item(0).getTextContent(),
      pomDocument.getElementsByTagName("artifactId").item(0).getTextContent(),
      pomDocument.getElementsByTagName("version").item(0).getTextContent());

  ImmutableSortedSet.Builder<MavenCoordinate> dependencyCoordinates =
      new ImmutableSortedSet.Builder<>(Ordering.usingToString());
  NodeList dependencies = pomDocument.getElementsByTagName("dependency");
  for (int i = 0; i < dependencies.getLength(); i++) {
    if (dependencies.item(i) instanceof Element) {
      Element dependency = (Element) dependencies.item(i);
      dependencyCoordinates.add(MavenCoordinate.create(
          dependency.getElementsByTagName("groupId").item(0).getTextContent(),
          dependency.getElementsByTagName("artifactId").item(0).getTextContent(),
          dependency.getElementsByTagName("version").item(0).getTextContent()));
    }
  }

  return new AutoValue_SdkMavenRepository_Pom(
      path, packaging, coordinate, dependencyCoordinates.build());
}
 
Example 16
Source File: PomUtil.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the text content of a specified child node (the first one) if it is present.
 *
 * @param parentNode the parent to query for the node.
 * @param nodeName the name of the child node from which the text content is requested.
 * @return the text content of the searched node.
 */
public static Optional<String> getChildNodeTextContent(Node parentNode, String nodeName) {
  String value = null;

  NodeList children = parentNode.getChildNodes();
  for (int i = 0; i < children.getLength(); i++) {
    Node n = children.item(i);
    if (Objects.equal(nodeName, n.getNodeName())) {
      value = n.getTextContent();
      break;
    }
  }

  return Optional.fromNullable(value);
}
 
Example 17
Source File: BaseIndicatorParameterManager.java    From TAcharting with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Stroke getStrokeOf(String key, String name) throws XPathExpressionException {
    Node node = getNodeForInstance(key);
    String command = String.format("./param[@name='%s']", name);
    XPathExpression expr = xPath.compile(command);
    Node paramNode = (Node) expr.evaluate(node,XPathConstants.NODE);
    String stroke = paramNode.getTextContent();
    if(stroke.equals("")){
        return null;
    }
    return StrokeType.valueOf(stroke.toUpperCase()).stroke;
}
 
Example 18
Source File: SituationTriggerRegistration.java    From container with Apache License 2.0 4 votes vote down vote up
private String getNodeContent(final Node node) {
    return node.getTextContent();
}
 
Example 19
Source File: LTTngControlServiceMI.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
static void getLoggerInfo(NodeList xmlEvents, List<ILoggerInfo> loggers, TraceDomainType domain) throws ExecutionException {
    ILoggerInfo loggerInfo = null;
    for (int i = 0; i < xmlEvents.getLength(); i++) {
        NodeList rawInfos = xmlEvents.item(i).getChildNodes();
        // Search for name
        if (xmlEvents.item(i).getNodeName().equalsIgnoreCase(MIStrings.EVENT)) {
            Node rawName = getFirstOf(rawInfos, MIStrings.NAME);
            if (rawName == null) {
                throw new ExecutionException(Messages.TraceControl_MiMissingRequiredError);
            }

            loggerInfo = new LoggerInfo(rawName.getTextContent());
            loggerInfo.setDomain(domain);

            // Basic information
            for (int j = 0; j < rawInfos.getLength(); j++) {
                Node infoNode = rawInfos.item(j);
                switch (infoNode.getNodeName()) {
                case MIStrings.LOGLEVEL_TYPE:
                    loggerInfo.setLogLevelType(LogLevelType.valueOfString(infoNode.getTextContent()));
                    break;
                case MIStrings.LOGLEVEL:
                    switch (domain) {
                    case JUL:
                        loggerInfo.setLogLevel(TraceJulLogLevel.valueOfString(infoNode.getTextContent()));
                        break;
                    case LOG4J:
                        loggerInfo.setLogLevel(TraceLog4jLogLevel.valueOfString(infoNode.getTextContent()));
                        break;
                    case PYTHON:
                        loggerInfo.setLogLevel(TracePythonLogLevel.valueOfString(infoNode.getTextContent()));
                        break;
                        //$CASES-OMITTED$
                    default:
                        break;
                    }
                    break;
                case MIStrings.ENABLED:
                    loggerInfo.setState(TraceEnablement.valueOfString(infoNode.getTextContent()));
                    break;
                default:
                    break;
                }
            }
            // Add the event
            loggers.add(loggerInfo);
        }
    }
}
 
Example 20
Source File: mxStylesheetCodec.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes the given mxStylesheet.
 */
public Object decode(mxCodec dec, Node node, Object into) {
  Object obj = null;

  if (node instanceof Element) {
    String id = ((Element)node).getAttribute("id");
    obj = dec.objects.get(id);

    if (obj == null) {
      obj = into;

      if (obj == null) {
        obj = cloneTemplate(node);
      }

      if (id != null && id.length() > 0) {
        dec.putObject(id, obj);
      }
    }

    node = node.getFirstChild();

    while (node != null) {
      if (!processInclude(dec, node, obj) && node.getNodeName().equals("add") && node instanceof Element) {
        String as = ((Element)node).getAttribute("as");

        if (as != null && as.length() > 0) {
          String extend = ((Element)node).getAttribute("extend");
          Map<String, Object> style = (extend != null) ? ((mxStylesheet)obj).getStyles().get(extend) : null;

          if (style == null) {
            style = new Hashtable<String, Object>();
          }
          else {
            style = new Hashtable<String, Object>(style);
          }

          Node entry = node.getFirstChild();

          while (entry != null) {
            if (entry instanceof Element) {
              Element entryElement = (Element)entry;
              String key = entryElement.getAttribute("as");

              if (entry.getNodeName().equals("add")) {
                String text = entry.getTextContent();
                Object value = null;

                if (text != null && text.length() > 0) {
                  value = mxUtils.eval(text);
                }
                else {
                  value = entryElement.getAttribute("value");

                }

                if (value != null) {
                  style.put(key, value);
                }
              }
              else if (entry.getNodeName().equals("remove")) {
                style.remove(key);
              }
            }

            entry = entry.getNextSibling();
          }

          ((mxStylesheet)obj).putCellStyle(as, style);
        }
      }

      node = node.getNextSibling();
    }
  }

  return obj;
}