@Get public Representation toXml() throws IOException { // Create a new DOM representation DomRepresentation result = new DomRepresentation(); // Ensure pretty printing result.setIndenting(true); // Retrieve the DOM document to populate Document doc = result.getDocument(); // Append the root node Node mailElt = doc.createElement("mail"); doc.appendChild(mailElt); // Append the child nodes and set their text content Node statusElt = doc.createElement("status"); statusElt.setTextContent("received"); mailElt.appendChild(statusElt); Node subjectElt = doc.createElement("subject"); subjectElt.setTextContent("Message to self"); mailElt.appendChild(subjectElt); Node contentElt = doc.createElement("content"); contentElt.setTextContent("Doh!"); mailElt.appendChild(contentElt); Node accountRefElt = doc.createElement("accountRef"); accountRefElt.setTextContent(new Reference(getReference(), "..").getTargetRef().toString()); mailElt.appendChild(accountRefElt); return result; }
Node create(Node parent, Document doc) throws ThinklabException { Node ret = doc.createElement(tag); if (attrs != null) for (Pair<String, String> a : attrs) { Attr attr = doc.createAttribute(a.getFirst()); attr.setValue(a.getSecond()); ((Element) ret).setAttributeNode(attr); } for (Object o : contents) { if (o instanceof String) { String text = (String) o; XMLDocument.setTextContent(doc, ret, text); } else if (o instanceof Collection<?>) { for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) { Object no = it.next(); if (!(no instanceof XmlNode)) { throw new ThinklabValidationException("XML.node: collections must be of XmlNode"); } ret.appendChild(((XmlNode) no).create(ret, doc)); } } else if (o instanceof XmlNode) { ret.appendChild(((XmlNode) o).create(ret, doc)); } } return ret; }
/** * Print out report of .jars found in a classpath. * * <p>Takes the information encoded from a checkPathForJars() call and dumps it out to our * PrintWriter. * * @param container Node to append our report to * @param factory Document providing createElement, etc. services * @param v Vector of Hashtables of .jar file info * @param desc description to print out in header * @return false if OK, true if any .jars were reported as having errors * @see #checkPathForJars(String, String[]) */ protected boolean appendFoundJars(Node container, Document factory, Vector v, String desc) { if ((null == v) || (v.size() < 1)) return false; boolean errors = false; for (int i = 0; i < v.size(); i++) { Hashtable subhash = (Hashtable) v.elementAt(i); for (Enumeration keys = subhash.keys(); keys.hasMoreElements(); /* no increment portion */ ) { Object key = keys.nextElement(); try { String keyStr = (String) key; if (keyStr.startsWith(ERROR)) { errors = true; } Element node = factory.createElement("foundJar"); node.setAttribute("name", keyStr.substring(0, keyStr.indexOf("-"))); node.setAttribute("desc", keyStr.substring(keyStr.indexOf("-") + 1)); node.appendChild(factory.createTextNode((String) subhash.get(keyStr))); container.appendChild(node); } catch (Exception e) { errors = true; Element node = factory.createElement("foundJar"); node.appendChild( factory.createTextNode(ERROR + " Reading " + key + " threw: " + e.toString())); container.appendChild(node); } } } return errors; }
void define(Node self, Document doc) throws ThinklabException { if (attrs != null) for (Pair<String, String> a : attrs) { Attr attr = doc.createAttribute(a.getFirst()); attr.setValue(a.getSecond()); ((Element) self).setAttributeNode(attr); } for (Object o : contents) { if (o instanceof String) { String text = (String) o; XMLDocument.setTextContent(doc, self, text); } else if (o instanceof Collection<?>) { for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) { Object no = it.next(); if (no instanceof XmlNode) { self.appendChild(((XmlNode) no).create(self, doc)); } else if (no instanceof Polylist) { self.appendChild(((Polylist) no).createXmlNode().create(self, doc)); } else { throw new ThinklabValidationException( "XML.node: collections must be of XmlNode or Polylist"); } } } else if (o instanceof XmlNode) { self.appendChild(((XmlNode) o).create(self, doc)); } else if (o instanceof Polylist) { self.appendChild(((Polylist) o).createXmlNode().create(self, doc)); } } }
/** * @param root * @param node */ private void writeRecursive(org.w3c.dom.Node target, Node source) { Document owned = target.getOwnerDocument(); if (owned == null) { owned = (Document) target; } org.w3c.dom.Node targetChild = null; if (source.text() != null) { targetChild = owned.createElement(source.name()); targetChild.appendChild(owned.createTextNode(source.text())); } else { targetChild = owned.createElement(source.name()); } target.appendChild(targetChild); for (Map.Entry<String, String> attribute : source.attributes().entrySet()) { Attr attr = owned.createAttribute(attribute.getKey()); attr.setValue(attribute.getValue()); targetChild.getAttributes().setNamedItem(attr); } for (Node sourceChild : source.children()) { writeRecursive(targetChild, sourceChild); } }
/** * Adds a compareType and pattern node as child elements to the provided parent node. * * @param xml the document to create xml elements from. * @param parent the parent to add to * @param compareType the name of the compare type (See {@link * com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.CompareType}) * @param pattern the pattern. */ void setXmlConfig(Document xml, Node parent, String compareType, String pattern) { Node compareTypeN = xml.createElement("compareType"); compareTypeN.setTextContent(compareType); parent.appendChild(compareTypeN); Node patternN = xml.createElement("pattern"); patternN.setTextContent(pattern); parent.appendChild(patternN); }
/** * Checks if child element has same owner document before appending to the parent, and imports it * to the parent's document if necessary. */ public static void appendChild(Node parent, Node child) { Document ownerDoc = getOwnerDocument(parent); if (child.getOwnerDocument() != ownerDoc) { parent.appendChild(ownerDoc.importNode(child, true)); } else { parent.appendChild(child); } }
public String addUser(String login, String password) { try { File file = new File(ServerSettings.STATISTICS_ROOT + File.separator + type + ".xml"); if (!file.exists()) { return "File doesn't exists: " + file.getAbsolutePath(); } Map<String, String> map = readUsersFromFile(); if (map == null) { return "Impossible to read xml file: " + file.getAbsolutePath(); } if (map.containsKey(login)) { return "User already exists"; } Document document = ResponseUtils.getXmlDocument(file); if (document == null) { return "Impossible to read xml file: " + file.getAbsolutePath(); } NodeList nodeList = document.getElementsByTagName("users"); Node newNode = document.createElement("user"); newNode.appendChild(document.createElement("login")); newNode.appendChild(document.createTextNode(login)); newNode.appendChild(document.createElement("password")); try { password = generateMD5(password); } catch (NoSuchAlgorithmException e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login); return "Impossible to generate MD5"; } catch (UnsupportedEncodingException e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login); return "Impossible to read password in UTF-8"; } newNode.appendChild(document.createTextNode(password)); nodeList.item(0).appendChild(newNode); NodeList list = document.getElementsByTagName("users"); Node node = list.item(0); DOMSource source = new DOMSource(node); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); FileWriter writer = new FileWriter(file); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.close(); return "User was added"; } catch (Throwable e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer( e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), ""); return "Unknown error: User wasn't added"; } }
@Override public void generate() { if (!comp.isEnable() || comp.isOnlyBuildComponentFile()) { return; } String projectBase = System.getProperty("projectBase"); String filename = comp.getComponentConfigFileURL(projectBase); // 读取文件 Document document = XmlFileHelper.read(filename); if (document == null) { env.getMessager().printError("读取以下文件失败:" + filename); return; } // 如果节点存在,更新节点 boolean exists = false; NodeList components = document.getElementsByTagName("component"); componentLabel: for (int i = 0; i < components.getLength(); i++) { Node component = components.item(i); for (int j = 0; j < component.getChildNodes().getLength(); j++) { Node child = component.getChildNodes().item(j); if ("component-type".equals(child.getNodeName()) && child.getTextContent().equals(comp.getComponentType())) { exists = true; } if ("component-class".equals(child.getNodeName()) && exists) { child.setTextContent(comp.getQualifiedComponentClassName()); break componentLabel; } } } // 如果节点不存在,插入节点 if (!exists) { Element newComponent = document.createElement("component"); Element newType = document.createElement("component-type"); newType.appendChild(document.createTextNode(comp.getComponentType())); Element newClass = document.createElement("component-class"); newClass.appendChild(document.createTextNode(comp.getQualifiedComponentClassName())); newComponent.appendChild(newType); newComponent.appendChild(newClass); Node facesConfig = document.getElementsByTagName("faces-config").item(0); facesConfig.appendChild(document.createTextNode("\t")); facesConfig.appendChild(newComponent); } // 写回文件 if (!XmlFileHelper.write(filename, document, false)) { env.getMessager().printError("写回以下文件失败:" + filename); } }
public static void addElement( Document document, Node node, String elementName, String elementData) { if ((document != null) && (node != null) && StringUtils.isNotNullOrEmpty(elementName)) { Node childNode = document.createElement(elementName); if (StringUtils.isNotNullOrEmpty(elementData)) { Node textNode = document.createTextNode(elementData); childNode.appendChild(textNode); } node.appendChild(childNode); } }
/** Process conditionals and non-repeat attributes on an element */ private void processElementInner(Node result, Element element) { TagHandler handler = registry.getHandlerFor(element); // An ugly special-case: <os:Repeat> will re-evaluate the "if" attribute // (as it should) for each loop of the repeat. Don't evaluate it here. if (!(handler instanceof RepeatTagHandler)) { Attr ifAttribute = element.getAttributeNode(ATTRIBUTE_IF); if (ifAttribute != null) { if (!evaluate(ifAttribute.getValue(), Boolean.class, false)) { return; } } } // TODO: the spec is silent on order of evaluation of "cur" relative // to "if" and "repeat" Attr curAttribute = element.getAttributeNode(ATTRIBUTE_CUR); Object oldCur = templateContext.getCur(); if (curAttribute != null) { templateContext.setCur(evaluate(curAttribute.getValue(), Object.class, null)); } if (handler != null) { handler.process(result, element, this); } else { // Be careful cloning nodes! If a target node belongs to a different document than the // template node then use importNode rather than cloneNode as that avoids side-effects // in UserDataHandlers where the cloned template node would belong to its original // document before being adopted by the target document. Element resultNode; if (element.getOwnerDocument() != result.getOwnerDocument()) { resultNode = (Element) result.getOwnerDocument().importNode(element, false); } else { resultNode = (Element) element.cloneNode(false); } clearSpecialAttributes(resultNode); Node additionalNode = processAttributes(resultNode); processChildNodes(resultNode, element); result.appendChild(resultNode); if (additionalNode != null) { result.appendChild(additionalNode); } } if (curAttribute != null) { templateContext.setCur(oldCur); } }
/** Write all stored informations in the tiff metadata tree. */ void flush() { // write GeoKeyDirectory // first line (4 int) contain the version and number of keys // Header={KeyDirectoryVersion, KeyRevision, MinorRevision, NumberOfKeys} final int[] values = new int[4 + 4 * entries.size()]; values[0] = GEOTIFF_VERSION; values[1] = REVISION_MAJOR; values[2] = REVISION_MINOR; values[3] = entries.size(); for (int i = 0, l = 4, n = entries.size(); i < n; i++, l += 4) { final KeyDirectoryEntry entry = entries.get(i); values[l] = entry.valueKey; values[l + 1] = entry.valuelocation; values[l + 2] = entry.valueNb; values[l + 3] = entry.valueOffset; } final Node nGeoKeyDir = createTiffField(getGeoKeyDirectoryTag()); nGeoKeyDir.appendChild(createTiffShorts(values)); ifd.appendChild(nGeoKeyDir); // write tagsets ifd.setAttribute( ATT_TAGSETS, BaselineTIFFTagSet.class.getName() + "," + GeoTIFFTagSet.class.getName()); if (nPixelScale != null) { ifd.appendChild(nPixelScale); } if (!tiePoints.isEmpty()) { ifd.appendChild(createModelTiePointsElement(tiePoints)); } else if (nTransform != null) { ifd.appendChild(nTransform); } if (!doubleValues.isEmpty()) { final Node nDoubles = createTiffField(getGeoDoubleParamsTag()); final Node nValues = createTiffDoubles(doubleValues); nDoubles.appendChild(nValues); ifd.appendChild(nDoubles); } if (asciiValues.length() > 0) { final Node nAsciis = createTiffField(getGeoAsciiParamsTag()); final Node nValues = createTiffAsciis(asciiValues.toString()); nAsciis.appendChild(nValues); ifd.appendChild(nAsciis); } }
public static void main(String[] args) { try { // Find the implementation DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); DOMImplementation impl = builder.getDOMImplementation(); // Create the document DocumentType svgDOCTYPE = impl.createDocumentType( "svg", "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"); Document doc = impl.createDocument("http://www.w3.org/2000/svg", "svg", svgDOCTYPE); // Fill the document Node rootElement = doc.getDocumentElement(); ProcessingInstruction xmlstylesheet = doc.createProcessingInstruction( "xml-stylesheet", "type=\"text/css\" href=\"standard.css\""); Comment comment = doc.createComment("An example from Chapter 10 of Processing XML with Java"); doc.insertBefore(comment, rootElement); doc.insertBefore(xmlstylesheet, rootElement); Node desc = doc.createElementNS("http://www.w3.org/2000/svg", "desc"); rootElement.appendChild(desc); Text descText = doc.createTextNode("An example from Processing XML with Java"); desc.appendChild(descText); // Serialize the document onto System.out TransformerFactory xformFactory = TransformerFactory.newInstance(); Transformer idTransform = xformFactory.newTransformer(); Source input = new DOMSource(doc); Result output = new StreamResult(System.out); idTransform.transform(input, output); } catch (FactoryConfigurationError e) { System.out.println("Could not locate a JAXP factory class"); } catch (ParserConfigurationException e) { System.out.println("Could not locate a JAXP DocumentBuilder class"); } catch (DOMException e) { System.err.println(e); } catch (TransformerConfigurationException e) { System.err.println(e); } catch (TransformerException e) { System.err.println(e); } }
/** * {@inheritDoc} In case children were to be removed between the time when this Change was added, * and the time when it was applied, maybe due to application of a RemoveChildrenChange, such * children are not re-instated. In case children were to be added between the time when this * Change was added, and the time when it was applied, maybe due to application of an * AddChildChange, such children are appended to the end of the list in preserving the order in * which they were added (that is they appear at the end). */ public void changeDocument(Node componentNode) { // build order map of of current Nodes, keyed by id LinkedHashMap<String, Node> currChildrenMap = new LinkedHashMap<String, Node>(13); Node currChild = componentNode.getFirstChild(); int fakeIndex = 0; while (currChild != null) { NamedNodeMap attributes = currChild.getAttributes(); String currKey = null; if (attributes != null) { Node idAttr = attributes.getNamedItem(_identifier); if (idAttr != null) { currKey = idAttr.getNodeValue(); } } // create a dummy key to maintain order of non-ided children if (currKey == null) { // =-= bts What about insignificant whitespace? currKey = Integer.valueOf(fakeIndex++).toString(); } currChildrenMap.put(currKey, currChild); // remove the children so that we can add them back in componentNode.removeChild(currChild); // next node is first node again currChild = componentNode.getFirstChild(); } // // put children back in, in order // for (String currReorderID : _childIds) { currChild = currChildrenMap.remove(currReorderID); if (currChild != null) { componentNode.appendChild(currChild); } } // add in all of the rest of the children in // relative order they originally appeared for (Map.Entry<String, Node> entry : currChildrenMap.entrySet()) { componentNode.appendChild(entry.getValue()); } }
private String getXML(String rootNodeName, Map<String, String> propertyMap) { Document doc = Xml.createDocument(); Node results = doc.createElement(rootNodeName); doc.appendChild(results); for (String key : propertyMap.keySet()) { Node itemChild = doc.createElement(key); itemChild.appendChild(doc.createTextNode(propertyMap.get(key))); results.appendChild(itemChild); } return Xml.writeDocumentToString(doc); }
static Node createModelTiePointsElement(final Collection<? extends TiePoint> tiePoints) { final Node nTiePoints = createTiffField(getModelTiePointTag()); final Node nValues = createNode(TAG_GEOTIFF_DOUBLES); nTiePoints.appendChild(nValues); for (final TiePoint tp : tiePoints) { nValues.appendChild(createTiffDouble(tp.rasterI)); nValues.appendChild(createTiffDouble(tp.rasterJ)); nValues.appendChild(createTiffDouble(tp.rasterK)); nValues.appendChild(createTiffDouble(tp.coverageX)); nValues.appendChild(createTiffDouble(tp.coverageY)); nValues.appendChild(createTiffDouble(tp.coverageZ)); } return nTiePoints; }
/** * @see * org.opencastproject.mediapackage.AbstractMediaPackageElement#toManifest(org.w3c.dom.Document, * MediaPackageSerializer) */ @Override public Node toManifest(Document document, MediaPackageSerializer serializer) { Node node = super.toManifest(document, serializer); // duration if (duration >= 0) { Node durationNode = document.createElement("duration"); durationNode.appendChild(document.createTextNode(Long.toString(duration))); node.appendChild(durationNode); } for (Stream s : audio) node.appendChild(s.toManifest(document, serializer)); for (Stream s : video) node.appendChild(s.toManifest(document, serializer)); return node; }
/** * Updates a node identified by xpath with a value. * * @param contextNode Node to be searched for the node * @param xpath query path to the node that has to be updated with the value * @param value value for the node */ public static void putValue(Node contextNode, String xpath, String value) { if (contextNode == null || value == null) { return; } Document doc = contextNode.getOwnerDocument(); if (doc == null) { return; } try { Node node = jaxenXPath.getSingleNode(contextNode, xpath); if (node != null) { switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: break; case Node.ATTRIBUTE_NODE: ((Attr) node).setValue(value.trim()); break; case Node.ELEMENT_NODE: // if node has no text nodes, create it if (!node.hasChildNodes()) { node.appendChild(doc.createTextNode(value.trim())); } else { NodeList childNodes = node.getChildNodes(); int length = childNodes.getLength(); for (int i = 0; i < length; i++) { Node child = childNodes.item(i); if (isText(child)) { child.setNodeValue(value.trim()); return; } } node.appendChild(doc.createTextNode(value.trim())); } break; } } } catch (Exception e) { } }
/** * * Returns a section as a complete htmlform, including the three required encounter tags. * * @param htmlForm * @param sectionIndex * @return * @throws Exception */ public static String getSectionAsFormXml(HtmlForm htmlForm, Integer sectionIndex) throws Exception{ Document doc = HtmlFormEntryUtil.stringToDocument(htmlForm.getXmlData()); NodeList nl = doc.getElementsByTagName("section"); Node sectionNode = null; try { sectionNode = nl.item(sectionIndex); } catch (Exception ex){ throw new RuntimeException("The section index that you've passed in is out of range. There are only " + nl.getLength() + " section tags in the document and you requested section tag " + sectionIndex); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc2 = db.newDocument(); Node formRoot = doc2.createElement("htmlform"); doc2.appendChild(formRoot); formRoot.appendChild(doc2.importNode(sectionNode, true)); if (doc2.getElementsByTagName("encounterLocation").getLength() == 0){ Node encLoc = doc2.createElement("encounterLocation"); formRoot.appendChild(encLoc); } if (doc2.getElementsByTagName("encounterDate").getLength() == 0){ Node encDate = doc2.createElement("encounterDate"); formRoot.appendChild(encDate); } if (doc2.getElementsByTagName("encounterProvider").getLength() == 0){ Node encDate = doc2.createElement("encounterProvider"); Element encDateElement = (Element) encDate; encDateElement.setAttribute("role","Provider"); formRoot.appendChild(encDate); } doc2.normalize(); try { DOMSource domSource = new DOMSource(doc2); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch(TransformerException ex) { ex.printStackTrace(); return null; } }
/** * Transforms the given list in a valid XHTML list by moving the nodes that are not allowed inside * <ul> and <ol> in <li> elements. * * @param list the list to be filtered */ private void filter(Element list) { // Iterate all the child nodes of the given list to see who's allowed and who's not allowed // inside it. Node child = list.getFirstChild(); Node previousListItem = null; while (child != null) { Node nextSibling = child.getNextSibling(); if (isAllowedInsideList(child)) { // Save a reference to the previous list item. Note that the previous list item is not // necessarily the // previous sibling. if (child.getNodeName().equalsIgnoreCase(TAG_LI)) { previousListItem = child; } } else { if (previousListItem == null) { // Create a new list item to be able to move the invalid child. previousListItem = list.getOwnerDocument().createElement(TAG_LI); list.insertBefore(previousListItem, child); // Hide the marker of the list item to make the list look the same after it is cleaned. ((Element) previousListItem).setAttribute(ATTRIBUTE_STYLE, "list-style-type: none"); } // Move the child node at the end of the previous list item because it is not allowed where // it is now. previousListItem.appendChild(child); } child = nextSibling; } }
void doApply( Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); DocumentFragment fragment = doc.createDocumentFragment(); format.apply(stylesheet, mode, context, pos, len, fragment, null); String f = Expr._string(context, Collections.singleton(fragment)); String value = format(f, compute(stylesheet, context, pos, len)); Text text = doc.createTextNode(value); if (nextSibling != null) { parent.insertBefore(text, nextSibling); } else { parent.appendChild(text); } // xsl:number doesn't process children if (next != null) { next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); } }
protected static void setValue(Node node, Document doc, String value) { if (null == node || node.getNodeType() != Node.ELEMENT_NODE) return; else { Node child = doc.createTextNode(escapeXml(value)); node.appendChild(child); } }
/** * Easily creates a new Node, containing Text and returns the new created Node. * * @param doc The Node to append to * @param elementName The Name of the new Node * @param elementText The Text to insert into the Node * @return The created Node */ public static Element createTextNode(Node doc, String elementName, String elementText) { Element elm = doc.getOwnerDocument().createElement(elementName); Text elmTxt = doc.getOwnerDocument().createTextNode(elementText); elm.appendChild(elmTxt); doc.appendChild(elm); return elm; }
/** * Pretty prints a node. * * @param doc The document the node comes from. * @param node The node that should be pretty printed. * @param prefix The prefix the node should get. */ private static void prettyPrint(Document doc, Node node, String prefix) { String childPrefix = prefix + " "; // Add the indenting to the children NodeList childList = node.getChildNodes(); boolean hasChildren = false; for (int i = childList.getLength() - 1; i >= 0; i--) { Node child = childList.item(i); boolean isNormalNode = (!child.getNodeName().startsWith("#")); if (isNormalNode) { // Add the indenting to this node Node textNode = doc.createTextNode(childPrefix); node.insertBefore(textNode, child); // pretty print the child's children prettyPrint(doc, child, childPrefix); hasChildren = true; } } // Add the indenting to the end tag if (hasChildren) { Node textNode = doc.createTextNode(prefix); node.appendChild(textNode); } }
private static Node getOrAddChildNode( Document doc, Node parentNode, String nodeName, int whichNode, int d) { doDebug( d, "> getOrAddChildNode name=" + nodeName + "@" + whichNode + " parentNode=" + nodeToString(parentNode)); d++; if (nodeName == null || parentNode == null) return null; // Check to see if we are somewhere in an index int begpos = nodeName.indexOf('['); int endpos = nodeName.indexOf(']'); // doDebug(d,"Looking for bracket ipos="+begpos+" endpos="+endpos); if (begpos > 0 && endpos > begpos && endpos < nodeName.length()) { String indStr = nodeName.substring(begpos + 1, endpos); doDebug(d, "Index String = " + indStr); nodeName = nodeName.substring(0, begpos); doDebug(d, "New Nodename=" + nodeName); Integer iVal = new Integer(indStr); doDebug(d, "Integer = " + iVal); whichNode = iVal; } NodeList nl = parentNode.getChildNodes(); int foundNodes = -1; if (nl != null) for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); // doDebug(d,"length= " +nl.getLength()+ " i="+i+" NT="+node.getNodeType()); // doDebug(d,"searching nn="+nodeName+" nc="+node.getNodeName()); if (node.getNodeType() == node.ELEMENT_NODE) { if (nodeName.equals(node.getNodeName())) { foundNodes++; d--; doDebug(d, "< getOrAddChildNode found name=" + nodeToString(node)); doDebug(d, "foundNodes = " + foundNodes + " looking for node=" + whichNode); if (foundNodes >= whichNode) return node; } } } Element newNode = null; while (foundNodes < whichNode) { foundNodes++; doDebug(d, "Adding node at position " + foundNodes + " moving toward " + whichNode); if (nodeName == null) continue; newNode = doc.createElement(nodeName); doDebug(d, "Adding " + nodeName + " at " + nodeToString(parentNode) + " in " + doc); parentNode.appendChild(newNode); doDebug(d, "xml=" + documentToString(doc, false)); doDebug(d, "getOrAddChildNode added newnode=" + nodeToString(newNode)); } d--; doDebug(d, "< getOrAddChildNode added newnode=" + nodeToString(newNode)); return newNode; }
/** * @param monitor * @throws Exception */ private void addServletToGwtXml(IProgressMonitor monitor) throws Exception { monitor = Util.getNonNullMonitor(monitor); try { monitor.beginTask("", 1); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File moduleFile = getModuleFile(); Document document = builder.parse(moduleFile); Node module = document.getDocumentElement(); Element newServlet = document.createElement("servlet"); newServlet.setAttribute("path", "/" + serviceUri); // $NON-NLS-2$ newServlet.setAttribute( "class", getPackageFragment().getElementName() + '.' + getTypeName() + "Impl"); // $NON-NLS-2$ module.appendChild(newServlet); Transformer writer = TransformerFactory.newInstance().newTransformer(); writer.transform(new DOMSource(document), new StreamResult(moduleFile)); } finally { monitor.done(); } }
private static void addKVP(Node parent, String key, String value) { Document doc = parent.getOwnerDocument(); Element e = doc.createElement("object"); addTextChild(e, "key", key); addTextChild(e, "value", value); parent.appendChild(e); }
/** * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>. * * @param parent */ public void makeElement(Node parent) { Document doc; if (parent instanceof Document) { doc = (Document) parent; } else { doc = parent.getOwnerDocument(); } Element element = doc.createElement("rem"); int size; if (definitionURL != null) { URelaxer2.setAttributePropertyByString( element, "http://www.w3.org/1998/Math/MathML", "definitionURL", definitionURL); } if (classValue != null) { URelaxer2.setAttributePropertyByString( element, "http://www.w3.org/1998/Math/MathML", "class", classValue); } if (style != null) { URelaxer2.setAttributePropertyByString( element, "http://www.w3.org/1998/Math/MathML", "style", style); } if (id != null) { URelaxer2.setAttributePropertyByString( element, "http://www.w3.org/1998/Math/MathML", "id", id); } if (other != null) { URelaxer2.setAttributePropertyByString( element, "http://www.w3.org/1998/Math/MathML", "other", other); } parent.appendChild(element); }
/** * Runs the test case. * * @throws Throwable Any uncaught exception causes test to fail */ public void runTest() throws Throwable { Document doc; NodeList genderList; Node genderNode; Node entText; EntityReference entReference; Node appendedChild; doc = (Document) load("staff", true); genderList = doc.getElementsByTagName("gender"); genderNode = genderList.item(2); entReference = doc.createEntityReference("ent3"); assertNotNull("createdEntRefNotNull", entReference); appendedChild = genderNode.appendChild(entReference); entText = entReference.getFirstChild(); assertNotNull("entTextNotNull", entText); { boolean success = false; try { ((CharacterData) /*Node */ entText).deleteData(1, 3); } catch (DOMException ex) { success = (ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR); } assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR", success); } }
private void injectProperties(MetriculatorXMLDocument xml) { Node propEl = xml.propertiesElement; Element themeEl = xml.doc.createElement("theme"); themeEl.setAttribute("name", theme); propEl.appendChild(themeEl); }