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

The following examples show how to use org.w3c.dom.Node#setNodeValue() . 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: XmlUtils.java    From butterfly with Apache License 2.0 6 votes vote down vote up
/**
 * Scrubs empty nodes from a document so we don't accidentally read them.
 * @param node The root node of the document to clean.
 */
public static void clean(final Node node) {
    final NodeList childrem = node.getChildNodes();

    for (int n = childrem.getLength() - 1; n >= 0; n--) {
        final Node child = childrem.item(n);
        final short nodeType = child.getNodeType();

        if (nodeType == Node.ELEMENT_NODE) {
            clean(child);
        } else if (nodeType == Node.TEXT_NODE) {
            final String trimmedNodeVal = child.getNodeValue().trim();

            if (trimmedNodeVal.length() == 0) {
                node.removeChild(child);
            } else {
                child.setNodeValue(trimmedNodeVal);
            }
        } else if (nodeType == Node.COMMENT_NODE) {
            node.removeChild(child);
        }
    }
}
 
Example 2
Source File: DOMCategory.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static NodeList getChildElements(Element self, String elementName) {
    List<Node> result = new ArrayList<Node>();
    NodeList nodeList = self.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element child = (Element) node;
            if ("*".equals(elementName) || child.getTagName().equals(elementName)) {
                result.add(child);
            }
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            String value = node.getNodeValue();
            if ((!isGlobalKeepIgnorableWhitespace() && value.trim().length() == 0) || isGlobalTrimWhitespace()) {
                value = value.trim();
            }
            if ("*".equals(elementName) && value.length() > 0) {
                node.setNodeValue(value);
                result.add(node);
            }
        }
    }
    return new NodesHolder(result);
}
 
Example 3
Source File: ResXmlPatcher.java    From ratel with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces package value with passed packageOriginal string
 *
 * @param file File for AndroidManifest.xml
 * @param packageOriginal Package name to replace
 * @throws AndrolibException
 */
public static void renameManifestPackage(File file, String packageOriginal) throws AndrolibException {
    try {
        Document doc = loadDocument(file);

        // Get the manifest line
        Node manifest = doc.getFirstChild();

        // update package attribute
        NamedNodeMap attr = manifest.getAttributes();
        Node nodeAttr = attr.getNamedItem("package");
        nodeAttr.setNodeValue(packageOriginal);
        saveDocument(file, doc);

    } catch (SAXException | ParserConfigurationException | IOException | TransformerException ignored) {
    }
}
 
Example 4
Source File: Inflate.java    From tomee with Apache License 2.0 6 votes vote down vote up
public boolean handleMessage(SOAPMessageContext mc) {
    try {
        final SOAPMessage message = mc.getMessage();
        final SOAPBody body = message.getSOAPBody();
        final String localName = body.getFirstChild().getLocalName();

        if ("sumResponse".equals(localName) || "multiplyResponse".equals(localName)) {
            final Node responseNode = body.getFirstChild();
            final Node returnNode = responseNode.getFirstChild();
            final Node intNode = returnNode.getFirstChild();

            final int value = new Integer(intNode.getNodeValue());
            intNode.setNodeValue(Integer.toString(value * 1000));
        }

        return true;
    } catch (SOAPException e) {
        return false;
    }
}
 
Example 5
Source File: DOMBuilder.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param trimWhitespace removes leading whitespace from the first resulting Node if it is a Text Node and
 *   removes trailing whitespace from the last Node if it is a Text Node.
 */
public void handleTokens(Element parentElement, List<FlowToken> siblingTokens, boolean trimWhitespace)
        throws SnuggleParseException {
    int childCountBefore = parentElement.getChildNodes().getLength();
    for (FlowToken content : siblingTokens) {
        handleToken(parentElement, content);
    }
    if (trimWhitespace) {
        NodeList childList = parentElement.getChildNodes();
        int childCountAfter = childList.getLength();
        int addedChildCount = childCountAfter - childCountBefore;
        if (addedChildCount>0) {
            int firstAddedChildIndex = childCountAfter - addedChildCount;
            int lastAddedChildIndex = childCountAfter - 1;
            
            Node firstAddedChildNode = childList.item(firstAddedChildIndex);
            if (firstAddedChildNode.getNodeType()==Node.TEXT_NODE) {
                firstAddedChildNode.setNodeValue(firstAddedChildNode.getNodeValue().replaceFirst("^\\s+", ""));
            }
            Node lastAddedChildNode = childList.item(lastAddedChildIndex);
            if (lastAddedChildNode.getNodeType()==Node.TEXT_NODE) {
                lastAddedChildNode.setNodeValue(lastAddedChildNode.getNodeValue().replaceFirst("\\s+$", ""));
            }
        }
    }
}
 
Example 6
Source File: Schema2BeansUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Merge child nodes
 * 
 * @param node     current node base
 * @param childNode child node if exist
 * @param foundBean child bean
 * @param currentChild current child node
 * @param patternChild current pattern child
 * @param nodeMap node map
 * @param document document
 * @param patternBean pattern bean
 * @param children list relevant childs current node base
 */
private static void mergeChildNodes(Node node, Node childNode, BaseBean foundBean,
        Node currentChild, Node patternChild, Map nodeMap, Document document,
        BaseBean patternBean, List children) {
    Node foundChild = childNode;
    if (foundChild == null) {
        foundChild = takeEqualNode(children, patternChild);
    }
    if (foundChild != null) {
        if (foundChild != currentChild) {
            node.removeChild(foundChild);
            node.insertBefore(foundChild, currentChild);
        }
        if (foundBean != null) {
            mergeBeans(nodeMap, foundBean, patternBean);
        } else if (isRelevantNode(foundChild) && foundChild.hasChildNodes()) {
            mergeNode(nodeMap, foundChild, patternChild);
        } else {
            foundChild.setNodeValue(patternChild.getNodeValue());
        }
    } else {
        Node child = document.importNode(patternChild, true);
        node.insertBefore(child, currentChild);
    }
}
 
Example 7
Source File: AbstractXmlNode.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public final void setAttribute(final String name, final String value) {
    final NamedNodeMap attributes = node.getAttributes();

    if (attributes == null) {
        return;
    }

    if (value == null) {
        // Remove the attribute if no value was specified.
        if (attributes.getNamedItem(name) != null) {
            attributes.removeNamedItem(name);
        }
    } else {
        // Remove a possibly existing attribute
        if (attributes.getNamedItem(name) != null) {
            attributes.removeNamedItem(name);
        }
        // Create a new attribute.
        final Document owner = node.getOwnerDocument();
        final Node item = owner.createAttribute(name);
        item.setNodeValue(value);
        attributes.setNamedItem(item);
    }
}
 
Example 8
Source File: DefaultParser.java    From tutorials with MIT License 6 votes vote down vote up
private void clean(Node node) {

        NodeList childs = node.getChildNodes();

        for (int n = childs.getLength() - 1; n >= 0; n--) {
            Node child = childs.item(n);
            short nodeType = child.getNodeType();

            if (nodeType == Node.ELEMENT_NODE)
                clean(child);
            else if (nodeType == Node.TEXT_NODE) {
                String trimmedNodeVal = child.getNodeValue().trim();
                if (trimmedNodeVal.length() == 0)
                    node.removeChild(child);
                else
                    child.setNodeValue(trimmedNodeVal);
            } else if (nodeType == Node.COMMENT_NODE)
                node.removeChild(child);
        }
    }
 
Example 9
Source File: NDataSourceHelper.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
private static List<Node> getWhitespaceNodes(Element element) {
	List<Node> nodes = new ArrayList<Node>();
	for (Node node : getNodesAsList(element)) {
		if (node.getNodeType() == Node.TEXT_NODE) {
			node.setNodeValue(node.getNodeValue().trim());
			if (node.getNodeValue().length() == 0) {
				nodes.add(node);
			}
		}
	}
	return nodes;
}
 
Example 10
Source File: XmlUtils.java    From semafor-semantic-parser with GNU General Public License v3.0 5 votes vote down vote up
public static void addAttribute(Document doc, String name, Element e, String value)
{
	Node attrNode = doc.createAttribute(name);
	attrNode.setNodeValue(value);
	NamedNodeMap attrs = e.getAttributes();
	attrs.setNamedItem(attrNode);
}
 
Example 11
Source File: TaggedRtf2Xliff.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compact.
 * @param list
 *            the list
 * @return the list< node>
 */
private List<Node> compact(List<Node> list) {
	List<Node> result = new ArrayList<Node>();
	for (int i = 0; i < list.size(); i++) {
		Node n = list.get(i);
		if (n.getNodeType() == Node.TEXT_NODE) {
			while (i + 1 < list.size() && (list.get(i + 1)).getNodeType() == Node.TEXT_NODE) {
				n.setNodeValue(n.getNodeValue() + (list.get(i + 1)).getNodeValue());
				i++;
			}
		}
		result.add(n);
	}
	return result;
}
 
Example 12
Source File: DOML3InputSourceFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public short acceptNode(Node n) {
    String localname = n.getLocalName();
    if (localname.equals("_test-04")) {
        Node child = n.getFirstChild();
        String text = child.getNodeValue();
        if (text.equals("T%e!s#t$")) {
            child.setNodeValue("T%E!S#T$");
        }
    }
    return FILTER_ACCEPT;
}
 
Example 13
Source File: ElementImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setValue(String value) {
    Node valueNode = getValueNodeStrict();
    if (valueNode != null) {
        valueNode.setNodeValue(value);
    } else {
        try {
            addTextNode(value);
        } catch (SOAPException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
 
Example 14
Source File: DomUtil.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/** Set or replace the text value
 */
public static void setText(Node node, String val) {
    Node chld=DomUtil.getChild(node, Node.TEXT_NODE);
    if( chld == null ) {
        Node textN=node.getOwnerDocument().createTextNode(val);
        node.appendChild(textN);
        return;
    }
    // change the value
    chld.setNodeValue(val);
}
 
Example 15
Source File: DOMCategory.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static void setValue(Element self, String value) {
    Node firstChild = self.getFirstChild();
    if (firstChild == null) {
        firstChild = self.getOwnerDocument().createTextNode(value);
        self.appendChild(firstChild);
    }
    firstChild.setNodeValue(value);
}
 
Example 16
Source File: XmlFileReader.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public FileReader replacePropertyValuesWith( String propertyName, String replacedValue )
{
    XPath xPath = XPathFactory.newInstance().newXPath();

    try
    {
        NodeList nodes = (NodeList) xPath.evaluate( "//*[@" + propertyName + "]", document, XPathConstants.NODESET );

        for ( int i = 0; i < nodes.getLength(); i++ )
        {
            Node node = nodes.item( i ).getAttributes().getNamedItem( propertyName );

            if ( replacedValue.equalsIgnoreCase( "uniqueid" ) )
            {
                node.setNodeValue( new IdGenerator().generateUniqueId() );
                continue;
            }
            node.setNodeValue( replacedValue );
        }

    }
    catch ( XPathExpressionException e )
    {
        e.printStackTrace();
    }

    return this;
}
 
Example 17
Source File: DSSXMLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Aligns indents for all children of the given node
 * @param parentNode {@link Node} to align children into
 * @return the given {@link Node} with aligned children
 */
public static Node alignChildrenIndents(Node parentNode) {
	if (parentNode.hasChildNodes()) {
		NodeList nodeChildren = parentNode.getChildNodes();
		String targetIndent = getTargetIndent(nodeChildren);
		if (targetIndent != null) {
			for (int i = 0; i < nodeChildren.getLength() - 1; i++) {
				Node node = nodeChildren.item(i);
				if (Node.TEXT_NODE == node.getNodeType()) {
					node.setNodeValue(targetIndent);
				}
			}
			Node lastChild = parentNode.getLastChild();
			targetIndent = targetIndent.substring(0, targetIndent.length() - DomUtils.TRANSFORMER_INDENT_NUMBER);
			switch (lastChild.getNodeType()) {
			case Node.ELEMENT_NODE:
				DomUtils.setTextNode(parentNode.getOwnerDocument(), (Element) parentNode, targetIndent);
				break;
			case Node.TEXT_NODE:
				lastChild.setNodeValue(targetIndent);
				break;
			default:
				break;
			}
		}
	}
	return parentNode;
}
 
Example 18
Source File: Layout.java    From screenstudio with GNU General Public License v3.0 4 votes vote down vote up
public void setAudioMicrophone(String value) {
    Node node = document.createAttribute("microphone");
    node.setNodeValue(value);
    audios.getAttributes().setNamedItem(node);

}
 
Example 19
Source File: CourgetteReporter.java    From courgette-jvm with MIT License 4 votes vote down vote up
private String formatXmlReport(List<String> reports, boolean mergeTestCaseName) {
    int failures = 0;
    int skipped = 0;
    int tests = 0;
    double time = 0.0;
    String testSuite = "Test Suite";

    final StringBuilder xmlBuilder = new StringBuilder();

    xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
    xmlBuilder.append("<testsuite failures=\"id:failures\" name=\"id:testSuite\" skipped=\"id:skipped\" tests=\"id:tests\" time=\"id:time\">\n\n");

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        for (String report : reports) {
            Document document = builder.parse(new InputSource(new StringReader(report)));

            if (document != null) {
                Element node = document.getDocumentElement();

                failures = failures + Integer.parseInt(node.getAttribute("failures"));
                skipped = skipped + Integer.parseInt(node.getAttribute("skipped"));
                tests = tests + Integer.parseInt(node.getAttribute("tests"));
                time = time + Double.parseDouble(node.getAttribute("time"));

                NodeList testCases = document.getElementsByTagName("testcase");

                if (testCases != null) {
                    for (int i = 0; i < testCases.getLength(); i++) {
                        Node testcase = testCases.item(i);

                        if (mergeTestCaseName) {
                            Node testClassName = testcase.getAttributes().getNamedItem("classname");
                            Node testName = testcase.getAttributes().getNamedItem("name");
                            String classNameValue = testClassName.getNodeValue();
                            String testNameValue = testName.getNodeValue();
                            testName.setNodeValue(classNameValue + ": " + testNameValue);
                        }

                        StringWriter sw = new StringWriter();
                        try {
                            Transformer t = TransformerFactory.newInstance().newTransformer();
                            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                            t.setOutputProperty(OutputKeys.INDENT, "yes");
                            t.transform(new DOMSource(testcase), new StreamResult(sw));

                            xmlBuilder.append(sw.toString()).append("\n");

                        } catch (TransformerException te) {
                            te.printStackTrace();
                        }
                    }
                }
            }
        }
    } catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
    }

    xmlBuilder.append("</testsuite>");

    if (courgetteProperties.isReportPortalPluginEnabled()) {
        testSuite = ReportPortalProperties.getInstance().getTestSuite();
    }

    return xmlBuilder.toString()
            .replace("id:failures", String.valueOf(failures))
            .replace("id:skipped", String.valueOf(skipped))
            .replace("id:tests", String.valueOf(tests))
            .replace("id:time", String.valueOf(time))
            .replace("id:testSuite", testSuite);
}
 
Example 20
Source File: Layout.java    From screenstudio with GNU General Public License v3.0 4 votes vote down vote up
public void setAudioBitrate(FFMpeg.AudioRate value) {
    Node node = document.createAttribute("audiobitrate");
    node.setNodeValue(value.name());
    audios.getAttributes().setNamedItem(node);
}