public void testCDATA() throws Exception { Document doc = XMLUtil.createDocument("root", null, null, null); Element e = doc.createElement("sometag"); doc.getDocumentElement().appendChild(e); String cdataContent = "!&<>*\n[[]]"; CDATASection cdata = doc.createCDATASection(cdataContent); e.appendChild(cdata); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc, baos, "UTF-8"); String data = baos.toString("UTF-8").replace("\r\n", "\n"); assertTrue("Can't find CDATA section", data.indexOf("<![CDATA[" + cdataContent + "]]>") != -1); // parse the data back to DOM Document doc2 = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null); NodeList nl = doc2.getElementsByTagName("sometag"); assertEquals("Wrong number of <sometag/> elements", 1, nl.getLength()); nl = nl.item(0).getChildNodes(); assertEquals("Wrong number of <sometag/> child elements", 1, nl.getLength()); Node child = nl.item(0); assertTrue("Expecting CDATASection node", child instanceof CDATASection); assertEquals("Wrong CDATASection content", cdataContent, ((CDATASection) child).getNodeValue()); }
private static void collectCDATASections(Node node, Set<String> cdataQNames) { if (node instanceof CDATASection) { Node parent = node.getParentNode(); if (parent != null) { String uri = parent.getNamespaceURI(); if (uri != null) { cdataQNames.add("{" + uri + "}" + parent.getNodeName()); //NOI18N } else { cdataQNames.add(parent.getNodeName()); } } } NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { collectCDATASections(children.item(i), cdataQNames); } }
/** * Write. * * @param node * the node */ protected void write(CDATASection node) { printWriter.print("<![CDATA["); //$NON-NLS-1$ String data = node.getNodeValue(); // XML parsers normalize line endings to '\n'. We should write // it out as it was in the original to avoid whitespace commits // on some version control systems int len = (data != null) ? data.length() : 0; for (int i = 0; i < len; i++) { char c = data.charAt(i); if (c == '\n') { printWriter.print(System.getProperty("line.separator")); //$NON-NLS-1$ } else { printWriter.print(c); } } printWriter.print("]]>"); //$NON-NLS-1$ printWriter.flush(); }
@Override public Element toXml(Document document) throws EngineException { Element element = super.toXml(document); // Storing the transaction WSDL type try { Element wsdlTypeElement = document.createElement("wsdltype"); if (wsdlType != null) { CDATASection cDATASection = document.createCDATASection(wsdlType); wsdlTypeElement.appendChild(cDATASection); element.appendChild(wsdlTypeElement); } } catch (NullPointerException e) { // Silently ignore } return element; }
@Override public Element toXml(Document document) throws EngineException { Element element = super.toXml(document); // Storing the sequence WSDL type try { Element wsdlTypeElement = document.createElement("wsdltype"); if (wsdlType != null) { CDATASection cDATASection = document.createCDATASection(wsdlType); wsdlTypeElement.appendChild(cDATASection); element.appendChild(wsdlTypeElement); } } catch(NullPointerException e) { // Silently ignore } return element; }
@Override protected void createStepNodeValue(Document doc, Element stepNode) throws EngineException { stepNode.setAttribute("key", key.isEmpty() ? "empty_key":StringUtils.normalize(key)); if (!key.isEmpty()) { Object object = value.getObject(this); if (object != null) { if ((object instanceof NodeList) && value.isUseSource()) { OutputFilter outputFilter = sequence.new OutputFilter(OutputOption.UsefullOnly); object = Sequence.ouputDomView((NodeList) object,outputFilter); } getSequence().context.httpSession.setAttribute(key, object); // Simple objects if ((object instanceof Boolean) || (object instanceof Integer) || (object instanceof Double) || (object instanceof Float) || (object instanceof Character) || (object instanceof Long) || (object instanceof Short) || (object instanceof Byte) || (object instanceof String)) { stepNode.setTextContent(ParameterUtils.toString(object)); } // Complex objects else { CDATASection cDATASection = doc.createCDATASection(ParameterUtils.toString(object)); stepNode.appendChild(cDATASection); } } } }
@Override public Element toXml(Document document) throws EngineException { Element element = super.toXml(document); // Storing the transaction "default" flag element.setAttribute("default", new Boolean(isDefault).toString()); // Storing the transaction handlers try { Element handlersElement = document.createElement("handlers"); if (handlers != null) { CDATASection cDATASection = document.createCDATASection(handlers); handlersElement.appendChild(cDATASection); element.appendChild(handlersElement); } } catch(NullPointerException e) { // Silently ignore } return element; }
@Override public Element toXml(org.w3c.dom.Document document) throws EngineException { Element element = super.toXml(document); // Storing the docdata try { Element dataElement = document.createElement("docdata"); if (docdata != null) { CDATASection cDATASection = document.createCDATASection(docdata); dataElement.appendChild(cDATASection); element.appendChild(dataElement); } } catch(NullPointerException e) { // Silently ignore } return element; }
@Override public Element toXml(Document document) throws EngineException { Element element = super.toXml(document); // Storing the transaction WSDL type try { Element wsdlTypeElement = document.createElement("wsdltype"); if (wsdlType != null) { CDATASection cDATASection = document.createCDATASection(wsdlType); wsdlTypeElement.appendChild(cDATASection); element.appendChild(wsdlTypeElement); } } catch(NullPointerException e) { // Silently ignore } return element; }
/** * Checks if an CDATASection node is well-formed, by checking it's data * for well-formedness. Note that the presence of a CDATA termination mark * in the contents of a CDATASection is handled by the parameter * spli-cdata-sections * * @param data The contents of the comment node */ protected void isCDATASectionWellFormed(CDATASection node) { // Does the data valid XML character data Character invalidChar = isWFXMLChar(node.getData()); //if (!isWFXMLChar(node.getData(), invalidChar)) { if (invalidChar != null) { String msg = Utils.messages.createMessage( MsgKey.ER_WF_INVALID_CHARACTER_IN_CDATA, new Object[] { Integer.toHexString(Character.getNumericValue(invalidChar.charValue())) }); if (fErrorHandler != null) { fErrorHandler.handleError( new DOMErrorImpl( DOMError.SEVERITY_FATAL_ERROR, msg, MsgKey.ER_WF_INVALID_CHARACTER, null, null, null)); } } }
protected int moveToChild(final int currentChild) { content = getCurrentElement().getChildNodes().item(currentChild); if (content instanceof Text) { return CHARACTERS; } else if (content instanceof Element) { return START_ELEMENT; } else if (content instanceof CDATASection) { return CDATA; } else if (content instanceof Comment) { return CHARACTERS; } else if (content instanceof EntityReference) { return ENTITY_REFERENCE; } throw new IllegalStateException(); }
private String getTextValue(Node node) { if (node == null) return null; StringBuffer b = new StringBuffer(); if (node.getNodeType() == Node.TEXT_NODE) { return ((Text) node).getData(); } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { return ((CDATASection) node).getData(); } else { Node child = node.getFirstChild(); while (child != null) { b.append(getTextValue(child)); child = child.getNextSibling(); } } return b.toString(); }
public static void appendNode(Node node, StringBuffer buf) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: appendElement((Element) node, buf); break; case Node.TEXT_NODE: appendText((Text) node, buf); break; case Node.CDATA_SECTION_NODE: appendCDATASection((CDATASection) node, buf); break; case Node.ENTITY_REFERENCE_NODE: appendEntityReference((EntityReference) node, buf); break; } }
/** * Replace all text values of a {@link Node} with CDATA values. * * @param doc * the document to update * * @param node * the node to update */ public static void replaceTextWithCData( Document doc, Node node ) { if (node instanceof Text) { Text text = (Text) node; CDATASection cdata = doc.createCDATASection( text.getTextContent() ); Element parent = (Element) text.getParentNode(); parent.replaceChild( cdata, text ); } else if (node instanceof Element) { //LOGGER.debug( "ELEMENT " + element.getTagName() ); NodeList children = node.getChildNodes(); for (int i=0; i<children.getLength(); i++) { //LOGGER.debug( "> " + children.item( i ).getClass().getName() ); XmlUtils.replaceTextWithCData( doc, children.item( i ) ); } } }
static <R> R visitNode(Node node, NodeVisitor<R> visitor) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: return visitor.visitElement((Element) node); case Node.ATTRIBUTE_NODE: return visitor.visitAttr((Attr) node); case Node.TEXT_NODE: return visitor.visitText((Text) node); case Node.CDATA_SECTION_NODE: return visitor.visitCDATASection((CDATASection) node); case Node.ENTITY_REFERENCE_NODE: return visitor.visitEntityReference((EntityReference) node); case Node.ENTITY_NODE: return visitor.visitEntity((Entity) node); case Node.PROCESSING_INSTRUCTION_NODE: return visitor.visitProcessingInstruction((ProcessingInstruction) node); case Node.COMMENT_NODE: return visitor.visitComment((Comment) node); case Node.DOCUMENT_NODE: return visitor.visitDocument((Document) node); case Node.DOCUMENT_TYPE_NODE: return visitor.visitDocumentType((DocumentType) node); case Node.DOCUMENT_FRAGMENT_NODE: return visitor.visitDocumentFragment((DocumentFragment) node); case Node.NOTATION_NODE: return visitor.visitNotation((Notation) node); default: throw new RuntimeException(); } }
private void eliminateCDataRecurse(Element parent) throws Exception { NodeList childNdList = parent.getChildNodes(); for (int i = 0; i < childNdList.getLength(); i++) { Node n = childNdList.item(i); if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { eliminateCDataRecurse((Element) n); } else if (n.getNodeType() == org.w3c.dom.Node.CDATA_SECTION_NODE) { // might need to pull thsi out to a vector, and then replace // later // depending on how well behaved the node list is. CDATASection cdc = (CDATASection) n; String val = cdc.getNodeValue(); Node newText = fDoc.createTextNode(val); parent.replaceChild(newText, n); } } }
/** * 获取指定元素的文本(Trimed) * * @param element * 节点 * @return 节点的文本。xml转义符会被还原;两端空格会被截去。 */ public static String nodeText(Node element) { Node first = first(element, Node.TEXT_NODE, Node.CDATA_SECTION_NODE); if (first != null && first.getNodeType() == Node.CDATA_SECTION_NODE) { return ((CDATASection) first).getTextContent(); } StringBuilder sb = new StringBuilder(); if (first == null || StringUtils.isBlank(first.getTextContent())) { for (Node n : toArray(element.getChildNodes())) { if (n.getNodeType() == Node.TEXT_NODE) { sb.append(n.getTextContent()); } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) { sb.append(((CDATASection) n).getTextContent()); } } } else { sb.append(first.getTextContent()); } return StringUtils.trimToNull(StringEscapeUtils.unescapeHtml(sb.toString())); }
/** * 得到节点下全部的text文本内容 * * @param element * 元素节点 * @param withChildren * 如果为真,则将该节点下属所有子元素的文本合并起来返回 * @return 节点文本。xml转义符会被还原;两端空格会被截去。 */ public static String nodeText(Node element, boolean withChildren) { StringBuilder sb = new StringBuilder(); for (Node node : toArray(element.getChildNodes())) { if (node.getNodeType() == Node.TEXT_NODE) { sb.append(node.getNodeValue().trim()); } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { sb.append(((CDATASection) node).getTextContent()); } else if (withChildren) { if (node.getNodeType() == Node.ELEMENT_NODE) { sb.append(nodeText((Element) node, true)); } } } return sb.toString(); }
/** * 获取指定元素的文本(Trimed) * * @param element * @return */ public static String nodeText(Node element) { Node first = first(element, Node.TEXT_NODE, Node.CDATA_SECTION_NODE); if (first != null && first.getNodeType() == Node.CDATA_SECTION_NODE) { return ((CDATASection) first).getTextContent(); } StringBuilder sb = new StringBuilder(); if (first == null || StringUtils.isBlank(first.getTextContent())) { for (Node n : toArray(element.getChildNodes())) { if (n.getNodeType() == Node.TEXT_NODE) { sb.append(n.getTextContent()); } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) { sb.append(((CDATASection) n).getTextContent()); } } } else { sb.append(first.getTextContent()); } return StringUtils.trimToNull(StringEscapeUtils.unescapeHtml(sb.toString())); }
/** * 得到节点下全部的text文本内容 * * @param element * @param withChildren * :如果为真,则将该节点下属所有节点的文本合并起来返回 * @return */ public static String nodeText(Node element, boolean withChildren) { StringBuilder sb = new StringBuilder(); for (Node node : toArray(element.getChildNodes())) { if (node.getNodeType() == Node.TEXT_NODE) { sb.append(node.getNodeValue().trim()); } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { sb.append(((CDATASection) node).getTextContent()); } else if (withChildren) { if (node.getNodeType() == Node.ELEMENT_NODE) { sb.append(nodeText((Element) node, true)); } } } return sb.toString(); }
public void testInvalidCharactersCdata() throws Exception { ErrorRecorder errorRecorder = new ErrorRecorder(); domConfiguration.setParameter("cdata-sections", true); domConfiguration.setParameter("error-handler", errorRecorder); domConfiguration.setParameter("namespaces", false); Element root = document.createElement("foo"); document.appendChild(root); CDATASection cdata = document.createCDATASection(""); root.appendChild(cdata); for (int c = 0; c <= Character.MAX_VALUE; c++) { cdata.setData(new String(new char[]{ 'A', 'B', (char) c })); document.normalizeDocument(); if (isValid((char) c)) { assertEquals(Collections.<DOMError>emptyList(), errorRecorder.errors); } else { errorRecorder.assertAllErrors("For character " + c, DOMError.SEVERITY_ERROR, "wf-invalid-character"); } } }
public void postRenderAction(SVGSVGElement root) { if (wcFont.isWebSafe()) return; Document document = root.getOwnerDocument(); Element defs = root.getElementById(SVGSyntax.ID_PREFIX_GENERIC_DEFS); Element style = document.createElementNS(SVGSyntax.SVG_NAMESPACE_URI, SVGSyntax.SVG_STYLE_TAG); style.setAttributeNS(null, SVGSyntax.SVG_TYPE_ATTRIBUTE, "text/css"); CDATASection styleSheet = document.createCDATASection(""); Font font = FontUtils.getFont(); styleSheet.setData("@font-face { font-family: '" + font.getFamily() + "'; src: url('static/fonts/" + wcFont.getName() + ".ttf');}"); style.appendChild(styleSheet); defs.appendChild(style); }
public WOElement buildNode(final Node _node) { if (_node == null) return null; switch (_node.getNodeType()) { case Node.ELEMENT_NODE: return this.buildElement((Element)_node); case Node.TEXT_NODE: return this.buildText((Text)_node); case Node.CDATA_SECTION_NODE: return this.buildCDATASection((CDATASection)_node); case Node.COMMENT_NODE: return this.buildComment((Comment)_node); case Node.DOCUMENT_NODE: return this.buildDocument((Document)_node); } log.error("unsupported XHTML node type: " + _node); return null; }
/** * @param xmlNode XML node * @param xmlStreamWriter XML stream writer * @throws XMLStreamException the XML stream exception */ public static void writeNode(Node xmlNode, XMLStreamWriter xmlStreamWriter) throws XMLStreamException { if (xmlNode instanceof Element) { addElement((Element) xmlNode, xmlStreamWriter); } else if (xmlNode instanceof Text) { xmlStreamWriter.writeCharacters(xmlNode.getNodeValue()); } else if (xmlNode instanceof CDATASection) { xmlStreamWriter.writeCData(((CDATASection) xmlNode).getData()); } else if (xmlNode instanceof Comment) { xmlStreamWriter.writeComment(((Comment) xmlNode).getData()); } else if (xmlNode instanceof EntityReference) { xmlStreamWriter.writeEntityRef(xmlNode.getNodeValue()); } else if (xmlNode instanceof ProcessingInstruction) { ProcessingInstruction procInst = (ProcessingInstruction) xmlNode; xmlStreamWriter.writeProcessingInstruction(procInst.getTarget(), procInst.getData()); } else if (xmlNode instanceof Document) { writeToDocument((Document) xmlNode, xmlStreamWriter); } }
/** * * @param xmlNode * @param xmlStreamWriter * @throws XMLStreamException */ public static void writeNode(Node xmlNode, XMLStreamWriter xmlStreamWriter) throws XMLStreamException { if (xmlNode instanceof Element) { addElement((Element) xmlNode, xmlStreamWriter); } else if (xmlNode instanceof Text) { xmlStreamWriter.writeCharacters(((Text) xmlNode).getNodeValue()); } else if (xmlNode instanceof CDATASection) { xmlStreamWriter.writeCData(((CDATASection) xmlNode).getData()); } else if (xmlNode instanceof Comment) { xmlStreamWriter.writeComment(((Comment) xmlNode).getData()); } else if (xmlNode instanceof EntityReference) { xmlStreamWriter.writeEntityRef(((EntityReference) xmlNode) .getNodeValue()); } else if (xmlNode instanceof ProcessingInstruction) { ProcessingInstruction procInst = (ProcessingInstruction) xmlNode; xmlStreamWriter.writeProcessingInstruction(procInst.getTarget(), procInst.getData()); } else if (xmlNode instanceof Document) { writeToDocument((Document) xmlNode, xmlStreamWriter); } }
/** * Formats a text or CDATA node for {@link #getShortString}. * * @param sb the builder to append to * @param aNode the text or CDATA node * * @since XMLUnit 2.4.0 */ protected void appendText(StringBuilder sb, Text aNode) { sb.append("<") .append(aNode.getParentNode().getNodeName()) .append(" ...>"); if (aNode instanceof CDATASection) { sb.append("<![CDATA[") .append(aNode.getNodeValue()) .append("]]>"); } else { sb.append(aNode.getNodeValue()); } sb.append("</") .append(aNode.getParentNode().getNodeName()) .append(">"); }
@SuppressWarnings("squid:S1166") // Exception caught and handled private Response writeError(Response.Status httpStatus, final String msg) { try { Document doc; final DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = dBF.newDocumentBuilder(); doc = builder.newDocument(); final Element ser = doc.createElement("ServiceExceptionReport"); doc.appendChild(ser); ser.setAttribute("version", WMS_VERSION); final Element se = XmlUtils.createElement(ser, "ServiceException"); CDATASection msgNode = doc.createCDATASection(msg); se.appendChild(msgNode); DOMSource source = new DOMSource(doc); return Response.status(httpStatus).entity(source).build(); } catch (ParserConfigurationException ignored) { } // Fallback in case there is an XML exception above return Response.status(httpStatus).entity(msg).build(); }
/** * Returns the constructed Node representing an attribute. * * @return */ protected AttributeDTO getAttribute() { AttributeBlobDTO attributeBlobDTO = (AttributeBlobDTO) super.getAttribute(); try { // get the attribute info to create a new attribute Node cdata = ( (Node) ConversionFacade.getXPath().evaluate(Elements.ATTRIBUTE_NAME.getLabel(), properties, XPathConstants.NODE) ).getFirstChild(); byte[] value = new byte[0]; if (cdata != null && cdata instanceof CDATASection) { value = Base64.decode(cdata.getTextContent()); attributeBlobDTO.setValue(value); } return attributeBlobDTO; } catch (XPathExpressionException ex) { String errString = "Improper XPath expression: " + ex.getMessage(); CommonExceptionProcessor.processException(ExceptionConstants.ConversionException.getExceptionClass(), errString, ex); } return null; }
private void injectTooltip(Element svgRoot) { Document doc = svgRoot.getOwnerDocument(); Element svgScript = doc.createElementNS(null, SVG_SCRIPT_TAG); CDATASection cdata = doc.createCDATASection(script()); svgScript.appendChild(cdata); svgRoot.insertBefore(svgScript, svgRoot.getFirstChild()); svgRoot.setAttributeNS(null, SVG_ONLOAD_ATTRIBUTE, "init(evt)"); Element ttBackground = doc.createElementNS(null, SVG_RECT_TAG); ttBackground.setAttributeNS(null, "id", "tooltip_bg"); ttBackground.setAttributeNS(null, "class", "tooltip_bg"); ttBackground.setAttributeNS(null, "height", "17"); ttBackground.setAttributeNS(null, "width", "1"); ttBackground.setAttributeNS(null, "visibility", "hidden"); ttBackground.setAttributeNS(null, "style", "fill: white;stroke: black;stroke-width: 1;opacity: 0.85;"); Element ttText = doc.createElementNS(null, SVG_TEXT_TAG); ttText.setAttributeNS(null, "id", "tooltip"); ttText.setAttributeNS(null, "class", "tooltip"); ttText.setAttributeNS(null, "visibility", "hidden"); ttText.setAttributeNS(null, "style", "font-size: 10px;font-family: sans-serif;stroke: none;"); ttText.appendChild(doc.createTextNode("tooltip")); svgRoot.appendChild(ttBackground); svgRoot.appendChild(ttText); }
/** * init node * * @param node * @param mTreeNode * @throws SAXException */ private void initNode(Node node, XMLDefaultMutableTreeNode mTreeNode) throws SAXException { switch (node.getNodeType()) { case Node.ELEMENT_NODE: initElementNode(node, mTreeNode); break; case Node.TEXT_NODE: initTextNode((Text) node, mTreeNode); break; case Node.CDATA_SECTION_NODE: initCDATASectionNode((CDATASection) node, mTreeNode); break; case Node.COMMENT_NODE: initCommentNode((Comment) node, mTreeNode); break; default: // if other node type, we will just skip it break; } }
private static Element getCorrectOptionNode(Document dom, Cell cell) { Element element = dom.createElement("CorrectOption"); try { String correctOptionValue = ""; int cellType = cell.getCellType(); if(cellType == Cell.CELL_TYPE_NUMERIC) { correctOptionValue = String.valueOf(cell.getNumericCellValue()); } else if(cellType == Cell.CELL_TYPE_STRING) { correctOptionValue = cell.getRichStringCellValue().toString(); } CDATASection text = dom.createCDATASection(correctOptionValue); element.appendChild(text); } catch (Exception e) { System.err.println("Unable to parse cell: " + cell.getRowIndex() + "," + cell.getColumnIndex()); System.err.println(cell.toString()); e.printStackTrace(); } return element; }
private static Element getQuestionTextNode(Document dom, Cell cell) { Element questionEle = dom.createElement("QuestionText"); try { String questionString = cell.getRichStringCellValue().toString(); questionString = replaceImageTags(questionString); CDATASection questionText = dom.createCDATASection(questionString); questionEle.appendChild(questionText); } catch (Exception e) { System.err.println("Unable to parse cell: " + cell.getRowIndex() + "," + cell.getColumnIndex()); System.err.println(cell.toString()); e.printStackTrace(); } return questionEle; }
private static Element getSectionNameNode(Document dom, Cell cell) { Element questionEle = dom.createElement("Section"); try { String sectionString = ""; int cellType = cell.getCellType(); if(cellType == Cell.CELL_TYPE_NUMERIC) { sectionString = String.valueOf(cell.getNumericCellValue()); } else if(cellType == Cell.CELL_TYPE_STRING) { sectionString = cell.getRichStringCellValue().toString(); } CDATASection section = dom.createCDATASection(sectionString); questionEle.appendChild(section); } catch (Exception e) { System.err.println("Unable to parse cell: " + cell.getRowIndex() + "," + cell.getColumnIndex()); System.err.println(cell.toString()); e.printStackTrace(); } return questionEle; }