List of usage examples for org.w3c.dom Node appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:net.d53dev.dslfy.web.service.GifService.java
private void configureGIFFrame(IIOMetadata meta, String delayTime, int imageIndex, String disposalMethod, int loopCount) { String metaFormat = meta.getNativeMetadataFormatName(); if (!"javax_imageio_gif_image_1.0".equals(metaFormat)) { throw new IllegalArgumentException("Unfamiliar gif metadata format: " + metaFormat); }//from ww w . jav a 2 s.c o m Node root = meta.getAsTree(metaFormat); Node child = root.getFirstChild(); while (child != null) { if ("GraphicControlExtension".equals(child.getNodeName())) break; child = child.getNextSibling(); } IIOMetadataNode gce = (IIOMetadataNode) child; gce.setAttribute("userDelay", "FALSE"); gce.setAttribute("delayTime", delayTime); gce.setAttribute("disposalMethod", disposalMethod); if (imageIndex == 0) { IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions"); IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension"); ae.setAttribute("applicationID", "NETSCAPE"); ae.setAttribute("authenticationCode", "2.0"); byte[] uo = new byte[] { 0x1, (byte) (loopCount & 0xFF), (byte) ((loopCount >> 8) & 0xFF) }; ae.setUserObject(uo); aes.appendChild(ae); root.appendChild(aes); } try { meta.setFromTree(metaFormat, root); } catch (IIOInvalidTreeException e) { throw new Error(e); } }
From source file:Main.java
public static void copyInto(Node src, Node dest) throws DOMException { Document factory = dest.getOwnerDocument(); //Node start = src; Node parent = null;//from w w w .j ava2 s .com Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.COMMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr) attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException( "can't copy node type, " + type + " (" + place.getNodeName() + ')'); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } else if (parent == null) { place = null; } else { // advance place = place.getNextSibling(); while (place == null && parent != null) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } }
From source file:Main.java
/** * The method inserts end-of-line+indentation Text nodes where indentation is necessary. * * @param node - node to be pretty formatted * @param identLevel - initial indentation level of the node * @param ident - additional indentation inside the node *//*w ww . j a va2 s .c om*/ private static void prettyFormat(Node node, String identLevel, String ident) { NodeList nodelist = node.getChildNodes(); int iStart = 0; Node item = nodelist.item(0); if (item != null) { short type = item.getNodeType(); if (type == Node.ELEMENT_NODE || type == Node.COMMENT_NODE) { Node newChild = node.getOwnerDocument().createTextNode(EOL_XML + identLevel + ident); node.insertBefore(newChild, item); iStart = 1; } } for (int i = iStart; i < nodelist.getLength(); i++) { item = nodelist.item(i); if (item != null) { short type = item.getNodeType(); if (type == Node.TEXT_NODE && item.getNodeValue().trim().length() == 0) { if (i + 1 < nodelist.getLength()) { item.setNodeValue(EOL_XML + identLevel + ident); } else { item.setNodeValue(EOL_XML + identLevel); } } else if (type == Node.ELEMENT_NODE) { prettyFormat(item, identLevel + ident, ident); if (i + 1 < nodelist.getLength()) { Node nextItem = nodelist.item(i + 1); if (nextItem != null) { short nextType = nextItem.getNodeType(); if (nextType == Node.ELEMENT_NODE || nextType == Node.COMMENT_NODE) { Node newChild = node.getOwnerDocument() .createTextNode(EOL_XML + identLevel + ident); node.insertBefore(newChild, nextItem); i++; continue; } } } else { Node newChild = node.getOwnerDocument().createTextNode(EOL_XML + identLevel); node.appendChild(newChild); i++; continue; } } } } }
From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java
private void copyNode(Node sourceNode, Node destinationNode) { Document destinationDoc = destinationNode.getOwnerDocument(); switch (sourceNode.getNodeType()) { case Node.TEXT_NODE: Text text = destinationDoc.createTextNode(sourceNode.getNodeValue()); destinationNode.appendChild(text); break;//from w w w .j a va 2 s .co m case Node.ELEMENT_NODE: Element element = destinationDoc.createElement(sourceNode.getNodeName()); destinationNode.appendChild(element); element.setTextContent(sourceNode.getNodeValue()); // Copy attributes NamedNodeMap attributes = sourceNode.getAttributes(); int nbAttributes = attributes.getLength(); for (int i = 0; i < nbAttributes; i++) { Node attribute = attributes.item(i); element.setAttribute(attribute.getNodeName(), attribute.getNodeValue()); } // Copy children nodes NodeList children = sourceNode.getChildNodes(); int nbChildren = children.getLength(); for (int i = 0; i < nbChildren; i++) { Node child = children.item(i); copyNode(child, element); } } }
From source file:ca.uqac.info.trace.generation.RandomTraceGenerator.java
@Override public EventTrace generate() { EventTrace trace = new EventTrace(); // We choose the number of messages to produce int n_messages = super.nextInt(m_maxMessages - m_minMessages) + m_minMessages; for (int i = 0; i < n_messages; i++) { Node n = trace.getNode(); Vector<String> available_params = new Vector<String>(); // We produce the list of available parameters for this message for (int j = 0; j < m_numParameters; j++) available_params.add("p" + j); // We choose the number of param-value pairs to generate int arity = super.nextInt(m_maxArity - m_minArity) + m_minArity; for (int j = 0; j < arity; j++) { // We generate as many param-value pairs as required int index = super.nextInt(available_params.size()); int value = super.nextInt(m_domainSize); if (m_minArity == 1 && m_maxArity == 1 && m_flatten) { // For traces of messages with fixed arity = 1, we // simply put the value as the text child of the "Event" // element n.appendChild(trace.createTextNode(new Integer(value).toString())); } else { Node el = trace.createElement("p" + index); el.appendChild(trace.createTextNode(new Integer(value).toString())); n.appendChild(el);/* www .j av a2 s. c o m*/ if (!m_isMultiValued) { // If event should not be multi-valued, then we remove // the chosen parameter from the list of available choices available_params.removeElementAt(index); } } } Event e = new Event(n); trace.add(e); } return trace; }
From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java
/** * <p>/* ww w .j a va2 s . co m*/ * Implementation of MathML unification. In the given W3C DOM represented * XML document find all maths nodes (see * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and * remember links to operator elements and other elements in * {@link #nodesByDepth} data structure. Then substitute them gradualy for * series of formulae with leaf elements substituted for a special * unification representing symbol {@code ◍} (for Presentation * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code ◐} * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}). * </p> * <p> * Resulting series of the original and unified MathML nodes is itself * encapsulated in a new element <unified-math> (see * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original * math element {@link Node} in the XML DOM representation the node is * attached to. * </p> * * @param mathNode W3C DOM XML document representation attached MathML node * to work on. * @param workInPlace If <code>true</code>, given <code>mathNode</code> will * be modified in place; if <code>false</code>, <code>mathNode</code> will * not be modified and series of modified nodes will be returned. * @param operatorUnification If <code>true</code> unify also operator * nodes, otherwise keep operator nodes intact. * @return <code>null</code> if <code>workInPlace</code> is * <code>false</code>; otherwise collection of unified versions of the * <code>mathNode</code> with key of the {@link HashMap} describing order * (level of unification) of elements in the collection. */ private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification, boolean workInPlace) { if (mathNode.getOwnerDocument() == null) { String msg = "The given node is not attached to any document."; if (mathNode.getNodeType() == Node.DOCUMENT_NODE) { msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead."; } throw new IllegalArgumentException(msg); } nodesByDepth = new HashMap<>(); Node unifiedMathNode = null; HashMap<Integer, Node> unifiedNodesList = null; Document unifiedMathDoc = null; if (workInPlace) { // New element encapsulating the series of unified formulae. unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_ROOT_ELEM); mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode); unifiedMathNode.appendChild(mathNode.cloneNode(true)); } else { unifiedNodesList = new HashMap<>(); // Create a new separate DOM to work over with imporeted clone of the node given by user unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true); mathNode = unifiedMathDoc.getDocumentElement(); } // Parse XML subtree starting at mathNode and remember elements by their depth. rememberLevelsOfNodes(mathNode, operatorUnification); // Build series of formulae of level by level unified MathML. NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS); int levelAttrCounter = 0; Collection<Attr> maxLevelAttrs = new LinkedList<>(); while (level.major > 0) { if (nodesByDepth.containsKey(level)) { if (unifyAtLevel(level)) { levelAttrCounter++; Node thisLevelMathNode = mathNode.cloneNode(true); Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR); Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR); maxLevelAttrs.add(maxLevelAttr); thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter)); ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr); ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr); if (workInPlace) { unifiedMathNode.appendChild(thisLevelMathNode); } else { // Create a new document for every node in the collection. unifiedNodesList.put(levelAttrCounter, DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true)); } } } level.minor--; if (level.minor <= 0) { level.major--; level.minor = NUMOFMINORLEVELS; } } for (Attr attr : maxLevelAttrs) { attr.setTextContent(String.valueOf((levelAttrCounter))); } if (workInPlace) { return null; } else { for (Node node : unifiedNodesList.values()) { Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS, UNIFIED_MATHML_MAX_LEVEL_ATTR); if (maxLevelAttr != null) { maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter))); } } return unifiedNodesList; } }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.geosearch.GeosearchDataImportWriter.java
private void addEntities() throws XPathExpressionException { Node document = getDocumentNode(); for (GeosearchTableVO geosearchTable : tables) { Element entity = generateEntity(geosearchTable, document); if (entity != null) { /*//from w w w. j a v a 2 s. c om * checks if the entity already exists. In that case, duplicates the * entity with other name and adds a comment */ boolean existsEntity = existsEntity(entity); if (existsEntity) { String entityName = entity.getAttribute("name"); int numSameEntities = getNumOfSameEntities(entity); entityName = entityName.concat("_duplicated_").concat(String.valueOf(numSameEntities)); entity.setAttribute("name", entityName); } document.appendChild(entity); insertTableNameComment(document, geosearchTable.getTable().getName(), entity); if (existsEntity) { String comment = "IMPORTANTE: Esta entidad ya se encuentra duplicada en el fichero dataImport." .concat(" Revise la configuracin ya que es posible que exista informacin duplicada"); insertComment(document, entity, comment); } } } }
From source file:eionet.gdem.qa.QAResultPostProcessor.java
/** * Parses div nodes and adds warning node to result * @param divElements Div elements/* w ww. j a v a 2 s .co m*/ * @param warnMessage Warning message * @return true if feedbacktext class is found * @throws XmlException If an error occurs. */ private boolean parseDivNodes(NodeList divElements, String warnMessage) throws XmlException { boolean feedBackDivFound = false; try { for (int i = 0; divElements != null && i < divElements.getLength(); i++) { Node divNode = divElements.item(i); Node classNode = divNode.getAttributes().getNamedItem("class"); if (classNode != null && classNode.getNodeValue().equalsIgnoreCase("feedbacktext")) { // found feedback div feedBackDivFound = true; Node firstChild = divNode.getFirstChild(); Document doc = divNode.getOwnerDocument(); Node warningNode = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource( new StringReader("<div class=\"error-msg\">" + warnMessage + "</div>"))) .getFirstChild(); warningNode = doc.importNode(warningNode, true); if (firstChild == null) { divNode.appendChild(warningNode); } else { warningNode = divNode.insertBefore(warningNode, firstChild); } // break; } } } catch (Exception e) { LOGGER.error("Error processing divNodes " + e); } return feedBackDivFound; }
From source file:com.rest4j.generator.Generator.java
void preprocess(List<ModelNode> graph, Node node) throws Exception { Node json = findChild(node, "json"); List<Node> models; if (json != null) { String type = json.getAttributes().getNamedItem("type").getTextContent(); models = computeModels(graph, type, false); } else {//from ww w .j ava 2s . c o m Node patch = findChild(node, "patch"); if (patch != null) { String type = patch.getAttributes().getNamedItem("type").getTextContent(); models = computeModels(graph, type, true); } else { return; } } for (Node model : models) { node.appendChild(model); } }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
private void setNumLines(Node domNode, int lines) { Node markerSequenceNode = getFirstElementByName(domNode, "markerSequence"); if (markerSequenceNode == null) { markerSequenceNode = new IIOMetadataNode("markerSequence"); domNode.appendChild(markerSequenceNode); }/*from w w w . j a va 2 s . c o m*/ Node sofNode = getFirstElementByName(markerSequenceNode, "sof"); if (sofNode == null) { sofNode = new IIOMetadataNode("sof"); markerSequenceNode.appendChild(sofNode); } Node attribute = getAttributeByName(sofNode, "numLines"); if (attribute == null) { attribute = new IIOMetadataNode("numLines"); sofNode.appendChild(attribute); } attribute.setNodeValue(Integer.toString(lines)); }