org.w3c.dom.CDATASection Java Examples

The following examples show how to use org.w3c.dom.CDATASection. 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: DOM3TreeWalker.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
        }
    }
}
 
Example #2
Source File: DOM3TreeWalker.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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));
        }
    }
}
 
Example #3
Source File: Grammar.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates a new CDATA section within this grammar.
 * @param data the CDATA to be added
 * @return the new created CDATA section
 * @since 0.7.5
 */
public CDATASection addCData(final String data) {
    final Document document = getOwnerDocument();
    final CDATASection node = document.createCDATASection(data);
    appendChild(node);
    return node;
}
 
Example #4
Source File: DefaultComparisonFormatter.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * 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(">");
}
 
Example #5
Source File: DOMWriter.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public void serializeNode(Node node) throws XMLStreamException {
  switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
      serializeDocument((Document) node);
      break;
    case Node.ELEMENT_NODE:
      serializeElement((Element) node);
      break;
    case Node.CDATA_SECTION_NODE:
      serializeCDATASection((CDATASection) node);
      break;
    case Node.TEXT_NODE:
      serializeText((Text) node);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      serializeProcessingInstruction((ProcessingInstruction) node);
      break;
    case Node.COMMENT_NODE:
      serializeComment((Comment) node);
      break;
    default:
      throw new MarkLogicInternalException(
        "Cannot process node type of: "+node.getClass().getName()
      );
  }
}
 
Example #6
Source File: HtmlElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void checkChildHierarchy(final Node childNode) throws DOMException {
    if (!((childNode instanceof Element) || (childNode instanceof Text)
        || (childNode instanceof Comment) || (childNode instanceof ProcessingInstruction)
        || (childNode instanceof CDATASection) || (childNode instanceof EntityReference))) {
        throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
            "The Element may not have a child of this type: " + childNode.getNodeType());
    }
    super.checkChildHierarchy(childNode);
}
 
Example #7
Source File: DOMFactory.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generates an xml element from this pojo. Translating the fields like described
 * in the class description.
 * @param document The document in which the nodes should be.
 * @param rootName This is to use another name for the root element than the
 * simple class name.
 * @param pojo The pojo to take the fields from.
 * @param attributes The fields which should be used as attributes and not
 * as elements.
 * @return The create element representing the provided pojo.
 * @throws ParserConfigurationException Might throw a ParserConfigurationException.
 * @throws IllegalAccessException Might throw a IllegalAccessException.
 * @throws InstantiationException Might throw a InstantiationException.
 */
public Element generateSimpleElement(final Document document, final String rootName,
        final Object pojo, final List<String> attributes) 
        throws ParserConfigurationException,
        IllegalAccessException, InstantiationException {
    Element rootNode = document.createElementNS(getDefaultNamespace(), rootName);
    List<Field> fields = getNonTransientSimpleFields(pojo.getClass());
    for (Field field : fields) {            
        field.setAccessible(true);
        String fieldName = field.getName();
                                
        if (field.get(pojo) != null) {
            
            if (!attributes.contains(fieldName)) {
                
                Element element = document.createElementNS(getDefaultNamespace(), getElementName(field));
                
                // handle CDATAs
                if (field.isAnnotationPresent(XmlValue.class)) {
                    CDATASection cdata = document.createCDATASection(field.get(pojo).toString());
                    element.appendChild(cdata);
                }
                else {
                  element.setTextContent(field.get(pojo).toString());                    
                }
                
                rootNode.appendChild(element);                    
            }
            else {
                rootNode.setAttribute(getAttributeName(field), field.get(pojo).toString());
            }
        }
    }
    return rootNode;
}
 
Example #8
Source File: XMLDOMWriterImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CDATA object @see org.w3c.dom.CDATASection.
 * @param data {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeCData(String data) throws XMLStreamException {
    if(data == null){
        throw new XMLStreamException("CDATA cannot be null");
    }

    CDATASection cdata = ownerDoc.createCDATASection(data);
    getNode().appendChild(cdata);
}
 
Example #9
Source File: XMLDOMWriterImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a CDATA object @see org.w3c.dom.CDATASection.
 * @param data {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeCData(String data) throws XMLStreamException {
    if(data == null){
        throw new XMLStreamException("CDATA cannot be null");
    }

    CDATASection cdata = ownerDoc.createCDATASection(data);
    getNode().appendChild(cdata);
}
 
Example #10
Source File: DOMDifferenceEngineTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test public void textAndCDataMatchRecursively() {
    Element e1 = doc.createElement("foo");
    Element e2 = doc.createElement("foo");
    Text fooText = doc.createTextNode("foo");
    e1.appendChild(fooText);
    CDATASection fooCDATASection = doc.createCDATASection("foo");
    e2.appendChild(fooCDATASection);
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e2, new XPathContext(),
                                e1, new XPathContext()));
}
 
Example #11
Source File: XMLDOMWriterImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a CDATA object @see org.w3c.dom.CDATASection.
 * @param data {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeCData(String data) throws XMLStreamException {
    if(data == null){
        throw new XMLStreamException("CDATA cannot be null");
    }

    CDATASection cdata = ownerDoc.createCDATASection(data);
    getNode().appendChild(cdata);
}
 
Example #12
Source File: DOMPrinter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void print(Node node) throws XMLStreamException {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        visitDocument((Document) node);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        visitDocumentFragment((DocumentFragment) node);
        break;
    case Node.ELEMENT_NODE:
        visitElement((Element) node);
        break;
    case Node.TEXT_NODE:
        visitText((Text) node);
        break;
    case Node.CDATA_SECTION_NODE:
        visitCDATASection((CDATASection) node);
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        visitProcessingInstruction((ProcessingInstruction) node);
        break;
    case Node.ENTITY_REFERENCE_NODE:
        visitReference((EntityReference) node);
        break;
    case Node.COMMENT_NODE:
        visitComment((Comment) node);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ATTRIBUTE_NODE:
    case Node.ENTITY_NODE:
    default:
        throw new XMLStreamException("Unexpected DOM Node Type "
            + node.getNodeType()
        );
    }
}
 
Example #13
Source File: GWTCompileSettings.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static String getElementText(Element element) {
  NodeList children = element.getChildNodes();
  for (int i = 0; i < children.getLength(); i++) {
    Node child = children.item(0);
    if (child.getNodeType() == Node.TEXT_NODE) {
      return ((Text) child).getNodeValue();
    } else if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
      return ((CDATASection) child).getNodeValue();
    }
  }
  return "";
}
 
Example #14
Source File: XMLDOMWriterImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a CDATA object @see org.w3c.dom.CDATASection.
 * @param data {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeCData(String data) throws XMLStreamException {
    if(data == null){
        throw new XMLStreamException("CDATA cannot be null");
    }

    CDATASection cdata = ownerDoc.createCDATASection(data);
    getNode().appendChild(cdata);
}
 
Example #15
Source File: test_DifferenceEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
public void testCompareCDATA() throws Exception {
    String expected = CDATA_A ;
    String actual = CDATA_B ;
    CDATASection control = document.createCDATASection(expected);
    CDATASection test = document.createCDATASection(actual);

    assertDifferentCDATA(control, test, CDATA_VALUE);
}
 
Example #16
Source File: WcsGenerator.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
@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", version.toString());
    final Element se = XmlUtils.createElement(ser, "ServiceException");
    CDATASection msgNode = doc.createCDATASection(msg);
    se.appendChild(msgNode);
    final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream();
    final PrintWriter out = new PrintWriter(xmlStream);
    DocumentUtils.writeDocument(doc, version, WCS_SERVICE, out);
    out.close();
    return Response
        .status(httpStatus)
        .header("Content-Type", MediaType.TEXT_XML)
        .entity(xmlStream.toString())
        .build();
  }
  catch (ParserConfigurationException | TransformerException ignored)
  {
  }
  // Fallback in case there is an XML exception above
  return Response.status(httpStatus).entity(msg).build();
}
 
Example #17
Source File: test_XpathNodeTracker.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
public void testNodes() throws Exception {
    Document doc = XMLUnit.newControlParser().newDocument();
    Element element = doc.createElementNS("http://example.com/xmlunit", "eg:root");
    xpathNodeTracker.visited(element);
    assertEquals("root element", "/root[1]", xpathNodeTracker.toXpathString());
            
    Attr attr = doc.createAttributeNS("http://example.com/xmlunit", "eg:type");
    attr.setValue("qwerty");
    element.setAttributeNodeNS(attr);
    xpathNodeTracker.visited(attr);
    assertEquals("root element attribute", "/root[1]/@type", xpathNodeTracker.toXpathString());             
            
    xpathNodeTracker.indent();
            
    Comment comment = doc.createComment("testing a comment");
    xpathNodeTracker.visited(comment);
    assertEquals("comment", "/root[1]/comment()[1]", xpathNodeTracker.toXpathString());

    ProcessingInstruction pi = doc.createProcessingInstruction("target","data");
    xpathNodeTracker.visited(pi);
    assertEquals("p-i", "/root[1]/processing-instruction()[1]", xpathNodeTracker.toXpathString());

    Text text = doc.createTextNode("some text");
    xpathNodeTracker.visited(text);
    assertEquals("text", "/root[1]/text()[1]", xpathNodeTracker.toXpathString());

    CDATASection cdata = doc.createCDATASection("some characters");
    xpathNodeTracker.visited(cdata);
    assertEquals("cdata", "/root[1]/text()[2]", xpathNodeTracker.toXpathString());
}
 
Example #18
Source File: DOMPrinter.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void print(Node node) throws XMLStreamException {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        visitDocument((Document) node);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        visitDocumentFragment((DocumentFragment) node);
        break;
    case Node.ELEMENT_NODE:
        visitElement((Element) node);
        break;
    case Node.TEXT_NODE:
        visitText((Text) node);
        break;
    case Node.CDATA_SECTION_NODE:
        visitCDATASection((CDATASection) node);
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        visitProcessingInstruction((ProcessingInstruction) node);
        break;
    case Node.ENTITY_REFERENCE_NODE:
        visitReference((EntityReference) node);
        break;
    case Node.COMMENT_NODE:
        visitComment((Comment) node);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ATTRIBUTE_NODE:
    case Node.ENTITY_NODE:
    default:
        throw new XMLStreamException("Unexpected DOM Node Type "
            + node.getNodeType()
        );
    }
}
 
Example #19
Source File: DbgpMessage.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected static String getNodeValue(Node node) {
    NodeList list = node.getChildNodes();
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < list.getLength(); i++) {
        Node child = list.item(i);
        if (child instanceof Text) {
            builder.append(child.getNodeValue());
        } else if (child instanceof CDATASection) {
            builder.append(child.getNodeValue());
        }
    }
    return replaceHtmlEntities(builder.toString());
}
 
Example #20
Source File: DOMPrinter.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void print(Node node) throws XMLStreamException {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        visitDocument((Document) node);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        visitDocumentFragment((DocumentFragment) node);
        break;
    case Node.ELEMENT_NODE:
        visitElement((Element) node);
        break;
    case Node.TEXT_NODE:
        visitText((Text) node);
        break;
    case Node.CDATA_SECTION_NODE:
        visitCDATASection((CDATASection) node);
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        visitProcessingInstruction((ProcessingInstruction) node);
        break;
    case Node.ENTITY_REFERENCE_NODE:
        visitReference((EntityReference) node);
        break;
    case Node.COMMENT_NODE:
        visitComment((Comment) node);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ATTRIBUTE_NODE:
    case Node.ENTITY_NODE:
    default:
        throw new XMLStreamException("Unexpected DOM Node Type "
            + node.getNodeType()
        );
    }
}
 
Example #21
Source File: ValidationTestCase.java    From simplexml with Apache License 2.0 5 votes vote down vote up
public boolean match(org.w3c.dom.Element element) {
   if(element != null) {
      Node value = element.getFirstChild();
      if(value instanceof CDATASection) {
         return value != null && value.getNodeValue().equals(text);
      }
      return false;
   }
   return false;
}
 
Example #22
Source File: DomHelper.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Adds the given formattedDocumentation within an XML documentation annotation under the supplied Node.
 * Only adds the documentation annotation if the formattedDocumentation is non-null and non-empty. The
 * documentation annotation is on the form:</p>
 * <pre>
 *     <code>
 *         &lt;xs:annotation&gt;
 *             &lt;xs:documentation&gt;(JavaDoc here, within a CDATA section)&lt;/xs:documentation&gt;
 *         &lt;/xs:annotation&gt;
 *     </code>
 * </pre>
 *
 * @param aNode                  The non-null Node to which an XML documentation annotation should be added.
 * @param formattedDocumentation The documentation text to add.
 */
public static void addXmlDocumentAnnotationTo(final Node aNode, final String formattedDocumentation) {

    if (aNode != null && formattedDocumentation != null && !formattedDocumentation.isEmpty()) {

        // Add the new Elements, as required.
        final Document doc = aNode.getOwnerDocument();
        final Element annotation = doc.createElementNS(
                XMLConstants.W3C_XML_SCHEMA_NS_URI, ANNOTATION_ELEMENT_NAME);
        final Element docElement = doc.createElementNS(
                XMLConstants.W3C_XML_SCHEMA_NS_URI, DOCUMENTATION_ELEMENT_NAME);
        final CDATASection xsdDocumentation = doc.createCDATASection(formattedDocumentation);

        // Set the prefixes
        annotation.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX);
        docElement.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX);

        // Inject the formattedDocumentation into the CDATA section.
        annotation.appendChild(docElement);
        final Node firstChildOfCurrentNode = aNode.getFirstChild();
        if (firstChildOfCurrentNode == null) {
            aNode.appendChild(annotation);
        } else {
            aNode.insertBefore(annotation, firstChildOfCurrentNode);
        }

        // All Done.
        docElement.appendChild(xsdDocumentation);
    }
}
 
Example #23
Source File: NodesTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void stripECWWorks() {
    Node orig = handleWsSetup();
    Node s = Nodes.stripElementContentWhitespace(orig);

    assertTrue(s instanceof Document);
    NodeList top = s.getChildNodes();
    assertEquals(1, top.getLength());
    assertTrue(top.item(0) instanceof Element);
    assertEquals("root", top.item(0).getNodeName());
    NodeList rootsChildren = top.item(0).getChildNodes();
    assertEquals(4, rootsChildren.getLength());
    assertTrue("should be comment, is " + rootsChildren.item(0).getClass(),
               rootsChildren.item(0) instanceof Comment);
    assertEquals(" trim\tme ",
                 ((Comment) rootsChildren.item(0)).getData());
    assertTrue("should be element, is " + rootsChildren.item(1).getClass(),
               rootsChildren.item(1) instanceof Element);
    assertEquals("child", rootsChildren.item(1).getNodeName());
    assertTrue("should be cdata, is " + rootsChildren.item(2).getClass(),
               rootsChildren.item(2) instanceof CDATASection);
    assertEquals(" trim me ",
                 ((CDATASection) rootsChildren.item(2)).getData());
    assertTrue("should be PI, is " + rootsChildren.item(3).getClass(),
               rootsChildren.item(3) instanceof ProcessingInstruction);
    assertEquals("trim me ",
                 ((ProcessingInstruction) rootsChildren.item(3)).getData());
    Node child = rootsChildren.item(1);
    NodeList grandChildren = child.getChildNodes();
    assertEquals(1, grandChildren.getLength());
    assertTrue("should be text, is " + grandChildren.item(0).getClass(),
               grandChildren.item(0) instanceof Text);
    assertEquals("\n trim me \n", ((Text) grandChildren.item(0)).getData());
    NamedNodeMap attrs = child.getAttributes();
    assertEquals(2, attrs.getLength());
    Attr a = (Attr) attrs.getNamedItem("attr");
    assertEquals(" trim me ", a.getValue());
    Attr a2 = (Attr) attrs.getNamedItem("attr2");
    assertEquals("not me", a2.getValue());
}
 
Example #24
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: The root contains a CDATASection with the
 * termination marker ']]&gt;', <br>
 * <b>name</b>: split-cdata-sections <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: A warning is reported when the section is
 * splitted
 */
@Test
public void testSplitCDATA001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();
    CDATASection cdata = doc.createCDATASection("text]" + "]>text");
    doc.getDocumentElement().appendChild(cdata);

    TestHandler testHandler = new TestHandler();
    config.setParameter("error-handler", testHandler);

    if (!config.canSetParameter("split-cdata-sections", Boolean.TRUE)) {
        Assert.fail("cannot set the parameters 'split-cdata-sections' to true");
    }
    config.setParameter("split-cdata-sections", Boolean.TRUE);

    doc.normalizeDocument();
    if (null == testHandler.getWarning()) {
        Assert.fail("no warning is reported");
    }

    return; // Status.passed("OK");

}
 
Example #25
Source File: DocumentComparator.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Appends the text content of the given node only if the node is an instance of {@link Text}
 * or related type ({@link CDATASection}, {@link Comment} or {@link ProcessingInstruction}).
 * Otherwise this method does nothing.
 *
 * @param  buffer  the buffer in which to append text content.
 * @param  node    the node for which to append text content.
 * @return {@code true} if a text has been formatted.
 */
private static boolean appendTextContent(final StringBuilder buffer, final Node node) {
    if (node instanceof Text ||
        node instanceof Comment ||
        node instanceof CDATASection ||
        node instanceof ProcessingInstruction)
    {
        buffer.append("=\"").append(node.getTextContent()).append('"');
        return true;
    }
    return false;
}
 
Example #26
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new createCDATASection.
 * @param data the data
 * @return the new CDATASection
 */
@JsxFunction
public Object createCDATASection(final String data) {
    final CDATASection node = getPage().createCDATASection(data);
    return getScriptableFor(node);
}
 
Example #27
Source File: SgmlPage.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public CDATASection createCDATASection(final String data) {
    return new DomCDataSection(this, data);
}
 
Example #28
Source File: DOMBuilder.java    From anthelion with Apache License 2.0 4 votes vote down vote up
/**
 * Receive notification of cdata.
 *
 * <p>The Parser will call this method to report each chunk of
 * character data.  SAX parsers may return all contiguous character
 * data in a single chunk, or they may split it into several
 * chunks; however, all of the characters in any single event
 * must come from the same external entity, so that the Locator
 * provides useful information.</p>
 *
 * <p>The application must not attempt to read from the array
 * outside of the specified range.</p>
 *
 * <p>Note that some parsers will report whitespace using the
 * ignorableWhitespace() method rather than this one (validating
 * parsers must do so).</p>
 *
 * @param ch The characters from the XML document.
 * @param start The start position in the array.
 * @param length The number of characters to read from the array.
 * @see #ignorableWhitespace
 * @see org.xml.sax.Locator
 */
public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException
{
  if(isOutsideDocElem()
     && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
    return;  // avoid DOM006 Hierarchy request error

  String s = new String(ch, start, length);

  // XXX [email protected]: modified from the original, to accomodate TagSoup. 
  Node n = m_currentNode.getLastChild();
  if (n instanceof CDATASection)
    ((CDATASection)n).appendData(s);
  else if (n instanceof Comment)
    ((Comment)n).appendData(s);
}
 
Example #29
Source File: DOMValidatorHelper.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/** Do processing for the start of a node. */
private void beginNode(Node node) {
    switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            fCurrentElement = node;
            // push namespace context
            fNamespaceContext.pushContext();
            // start element
            fillQName(fElementQName, node);
            processAttributes(node.getAttributes());
            fSchemaValidator.startElement(fElementQName, fAttributes, null);
            break;
        case Node.TEXT_NODE:
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.setIgnoringCharacters(true);
                sendCharactersToValidator(node.getNodeValue());
                fDOMValidatorHandler.setIgnoringCharacters(false);
                fDOMValidatorHandler.characters((Text) node);
            }
            else {
                sendCharactersToValidator(node.getNodeValue());
            }
            break;
        case Node.CDATA_SECTION_NODE:
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.setIgnoringCharacters(true);
                fSchemaValidator.startCDATA(null);
                sendCharactersToValidator(node.getNodeValue());
                fSchemaValidator.endCDATA(null);
                fDOMValidatorHandler.setIgnoringCharacters(false);
                fDOMValidatorHandler.cdata((CDATASection) node);
            }
            else {
                fSchemaValidator.startCDATA(null);
                sendCharactersToValidator(node.getNodeValue());
                fSchemaValidator.endCDATA(null);
            }
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            /**
             * The validator does nothing with processing instructions so bypass it.
             * Send the ProcessingInstruction node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.processingInstruction((ProcessingInstruction) node);
            }
            break;
        case Node.COMMENT_NODE:
            /**
             * The validator does nothing with comments so bypass it.
             * Send the Comment node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.comment((Comment) node);
            }
            break;
        case Node.DOCUMENT_TYPE_NODE:
            /**
             * Send the DocumentType node directly to the result builder.
             */
            if (fDOMValidatorHandler != null) {
                fDOMValidatorHandler.doctypeDecl((DocumentType) node);
            }
            break;
        default: // Ignore other node types.
            break;
    }
}
 
Example #30
Source File: DOMDocument.java    From lemminx with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public CDATASection createCDATASection(String data) throws DOMException {
	throw new UnsupportedOperationException();
}