List of usage examples for org.w3c.dom Node getNextSibling
public Node getNextSibling();
From source file:elaborate.editor.export.tei.TeiMaker.java
private int processEntry(int _pageno, Element body, String _currentFolio, ProjectEntry projectEntry) { int pageno = _pageno; String currentFolio = _currentFolio; String folio = StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio number"), "") + StringUtils.defaultIfBlank(projectEntry.getMetadataValue("Folio side"), ""); if (!currentFolio.equals(folio)) { pageno = addPb(body, pageno, projectEntry, folio); }/*from www. j ava2 s . co m*/ // addCb(body, projectEntry); currentFolio = folio; Element entryDiv = tei.createElement("div"); entryDiv.setAttribute("xml:id", "e" + projectEntry.getId()); entryDiv.setAttribute("n", projectEntry.getName()); addEntryInterpGrp(entryDiv, projectEntry); List<Transcription> orderedTranscriptions = Lists.newArrayList(projectEntry.getTranscriptions()); Collections.sort(orderedTranscriptions, ORDER_BY_TYPE); for (Transcription transcription : orderedTranscriptions) { HtmlTeiConverter htmlTeiConverter = new HtmlTeiConverter(transcription.getBody(), config, transcription.getTranscriptionType().getName(), entityManager); Node transcriptionNode = htmlTeiConverter.getContent(); Node importedTranscriptionNode = tei.importNode(transcriptionNode, true); Node child = importedTranscriptionNode.getFirstChild(); while (child != null) { Node nextSibling = child.getNextSibling(); if (child.getNodeName().equals("div") && child.hasChildNodes()) { entryDiv.appendChild(child); } child = nextSibling; } } body.appendChild(entryDiv); return pageno; }
From source file:importer.handler.post.stages.Discriminator.java
/** * Get the next true sibling of the given element * @param elem the element to get the next sibling of * @return the next true sibling of elem or null *//* w w w .j a v a 2 s . co m*/ Element nextTrueSibling(Element elem) { Node n = elem; while (elem != null) { n = n.getNextSibling(); if (n == null) elem = null; else if (n.getNodeType() == Node.ELEMENT_NODE) { Sibling s = siblings.get(n.getNodeName()); if (s != null) { String sName = s.getSibling(); String nName = n.getNodeName(); String eName = elem.getNodeName(); if (eName.equals(sName) || eName.equals(nName)) { elem = (Element) n; break; } else elem = null; } else elem = null; } else if (n.getNodeType() == Node.TEXT_NODE && !isWhitespace(n.getTextContent())) elem = null; } return elem; }
From source file:com.connectutb.xfuel.FuelPlanner.java
public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); }/*from ww w . ja v a2 s . co m*/ } } } return ""; }
From source file:com.amalto.core.history.accessor.UnaryFieldAccessor.java
private Element getElement() { Element element = null;// www . j av a 2s.co m Node parentNode = parent.getNode(); if (parentNode != null) { Node current = parentNode.getFirstChild(); while (current != null) { if (fieldName.equals(current.getNodeName())) { element = (Element) current; break; } current = current.getNextSibling(); } } return element; }
From source file:net.algart.simagis.imageio.IIOMetadataToJsonConverter.java
private JSONObject treeToJson(Node node) throws JSONException { JSONObject result = new JSONObject(); result.put("name", node.getNodeName()); result.put("value", node.getNodeValue()); final NamedNodeMap nodeAttributes = node.getAttributes(); if (nodeAttributes != null) { final int length = nodeAttributes.getLength(); if (length > 0) { JSONObject attributes = new JSONObject(); for (int k = 0; k < length; k++) { final Node nodeAttr = nodeAttributes.item(k); attributes.put(nodeAttr.getNodeName(), nodeAttr.getNodeValue()); }/* w ww.ja v a 2s. c o m*/ result.put("attributes", attributes); } } JSONObject compactChildren = null; for (String childrenName : COMPACTED_SIMILAR_CHILDREN_NAMES) { compactChildren = compactTIFFSimilarNodes(node, childrenName); if (compactChildren != null) { break; } } if (compactChildren != null) { result.put("joinedNodes", compactChildren); } else { Node child = node.getFirstChild(); if (child != null) { JSONArray nodes = new JSONArray(); do { nodes.put(treeToJson(child)); child = child.getNextSibling(); } while (child != null); result.put("nodes", nodes); } } if (node instanceof IIOMetadataNode) { result.put("userObject", iioNodeUserObjectToJson((IIOMetadataNode) node)); } return result; }
From source file:com.enonic.esl.xml.XMLTool.java
/** * Get an element's first sub-element. Will return null if root is null, root does not have any sub-elements. * * @param root Element the root element to search in * @return Element the first sub-element, or null if none found *///from www . ja v a 2s . c o m public static Element getFirstElement(Element root) { if (root == null) { return null; } Node n = root.getFirstChild(); while (n != null && n.getNodeType() != Node.ELEMENT_NODE) { n = n.getNextSibling(); } if (n != null) { return (Element) n; } return null; }
From source file:ApplyXPath.java
/** Process input args and execute the XPath. */ public void doMain(String[] args) throws Exception { filename = args[0];/*from w ww . ja v a 2 s . com*/ xpath = args[1]; if ((filename != null) && (filename.length() > 0) && (xpath != null) && (xpath.length() > 0)) { // Tell that we're loading classes and parsing, so the time it // takes to do this doesn't get confused with the time to do // the actual query and serialization. System.out.println("Loading classes, parsing " + filename + ", and setting up serializer"); // Set up a DOM tree to query. InputSource in = new InputSource(new FileInputStream(filename)); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); Document doc = dfactory.newDocumentBuilder().parse(in); // Set up an identity transformer to use as serializer. Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // Use the simple XPath API to select a nodeIterator. System.out.println("Querying DOM using " + xpath); NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath); // Serialize the found nodes to System.out. System.out.println("<output>"); Node n; while ((n = nl.nextNode()) != null) { if (isTextNode(n)) { // DOM may have more than one node corresponding to a // single XPath text node. Coalesce all contiguous text nodes // at this level StringBuffer sb = new StringBuffer(n.getNodeValue()); for (Node nn = n.getNextSibling(); isTextNode(nn); nn = nn.getNextSibling()) { sb.append(nn.getNodeValue()); } System.out.print(sb); } else { serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out))); } System.out.println(); } System.out.println("</output>"); } else { System.out.println("Bad input args: " + filename + ", " + xpath); } }
From source file:com.mirth.connect.model.converters.DICOMSerializer.java
@Override public String fromXML(String source) throws SerializerException { if (source == null || source.length() == 0) { return StringUtils.EMPTY; }/*w w w . j a v a 2 s. co m*/ try { // re-parse the xml to Mirth format Document document = documentSerializer.fromXML(source); Element element = document.getDocumentElement(); Node node = element.getChildNodes().item(0); // change back to <attr> tag for all tags under <dicom> tag while (node != null) { renameTagToAttr(document, node); node = node.getNextSibling(); } NodeList items = document.getElementsByTagName("item"); // change back to <attr> tag for all tags under <item> tags if (items != null) { for (int i = 0; i < items.getLength(); i++) { Node itemNode = items.item(i); if (itemNode.getChildNodes() != null) { NodeList itemNodes = itemNode.getChildNodes(); for (int j = 0; j < itemNodes.getLength(); j++) { Node nodeItem = itemNodes.item(j); renameTagToAttr(document, nodeItem); } } } } // find the charset String charset = null; Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0); if (charsetElement != null) { charset = charsetElement.getNodeValue(); } else { charset = "utf-8"; } // parse the Document into a DicomObject SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); DicomObject dicomObject = new BasicDicomObject(); ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject); byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset); parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler); return new String(Base64.encodeBase64Chunked(DICOMUtil.dicomObjectToByteArray(dicomObject))); } catch (Exception e) { throw new SerializerException(e); } }
From source file:com.mirth.connect.plugins.datatypes.dicom.DICOMSerializer.java
@Override public String fromXML(String source) throws MessageSerializerException { if (source == null || source.length() == 0) { return org.apache.commons.lang3.StringUtils.EMPTY; }// w w w . j a v a 2s. c om try { // re-parse the xml to Mirth format Document document = documentSerializer.fromXML(source); Element element = document.getDocumentElement(); Node node = element.getChildNodes().item(0); // change back to <attr> tag for all tags under <dicom> tag while (node != null) { renameTagToAttr(document, node); node = node.getNextSibling(); } NodeList items = document.getElementsByTagName("item"); // change back to <attr> tag for all tags under <item> tags if (items != null) { for (int i = 0; i < items.getLength(); i++) { Node itemNode = items.item(i); if (itemNode.getChildNodes() != null) { NodeList itemNodes = itemNode.getChildNodes(); for (int j = 0; j < itemNodes.getLength(); j++) { Node nodeItem = itemNodes.item(j); renameTagToAttr(document, nodeItem); } } } } // find the charset String charset = null; Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0); if (charsetElement != null) { charset = charsetElement.getNodeValue(); } else { charset = "utf-8"; } // parse the Document into a DicomObject SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); DicomObject dicomObject = new BasicDicomObject(); ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject); byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset); parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler); return StringUtils .newStringUsAscii(Base64Util.encodeBase64(DICOMConverter.dicomObjectToByteArray(dicomObject))); } catch (Exception e) { throw new MessageSerializerException("Error converting XML to DICOM", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to DICOM", e)); } }
From source file:DOM2SAX.java
/** * Writes a node using the given writer. * @param node node to serialize/* w ww . j av a 2s .c om*/ * @throws SAXException In case of a problem while writing XML */ private void writeNode(Node node) throws SAXException { if (node == null) { return; } switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE case Node.DOCUMENT_FRAGMENT_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: // These node types are ignored!!! break; case Node.CDATA_SECTION_NODE: final String cdata = node.getNodeValue(); if (lexicalHandler != null) { lexicalHandler.startCDATA(); contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); lexicalHandler.endCDATA(); } else { // in the case where there is no lex handler, we still // want the text of the cdate to make its way through. contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); } break; case Node.COMMENT_NODE: // should be handled!!! if (lexicalHandler != null) { final String value = node.getNodeValue(); lexicalHandler.comment(value.toCharArray(), 0, value.length()); } break; case Node.DOCUMENT_NODE: contentHandler.startDocument(); Node next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } contentHandler.endDocument(); break; case Node.ELEMENT_NODE: String prefix; List pushedPrefixes = new java.util.ArrayList(); final AttributesImpl attrs = new AttributesImpl(); final NamedNodeMap map = node.getAttributes(); final int length = map.getLength(); // Process all namespace declarations for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore everything but NS declarations here if (qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNodeValue(); final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } } // Process all other attributes for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore NS declarations here if (!qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNamespaceURI(); // Uri may be implicitly declared if (uriAttr != null) { final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } // Add attribute to list attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, "CDATA", attr.getNodeValue()); } } // Now process the element itself final String qname = node.getNodeName(); final String uri = node.getNamespaceURI(); final String localName = getLocalName(node); // Uri may be implicitly declared if (uri != null) { final int colon = qname.lastIndexOf(':'); prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uri)) { pushedPrefixes.add(prefix); } } // Generate SAX event to start element contentHandler.startElement(uri, localName, qname, attrs); // Traverse all child nodes of the element (if any) next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } // Generate SAX event to close element contentHandler.endElement(uri, localName, qname); // Generate endPrefixMapping() for all pushed prefixes final int nPushedPrefixes = pushedPrefixes.size(); for (int i = 0; i < nPushedPrefixes; i++) { endPrefixMapping((String) pushedPrefixes.get(i)); } break; case Node.PROCESSING_INSTRUCTION_NODE: contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: final String data = node.getNodeValue(); contentHandler.characters(data.toCharArray(), 0, data.length()); break; default: //nop } }