Java Code Examples for org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE

The following are Jave code examples for showing how to use PROCESSING_INSTRUCTION_NODE of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: OpenJSharp   File: XMLUtils.java   Source Code and License Vote up 6 votes
/**
 * Method getStrFromNode
 *
 * @param xpathnode
 * @return the string for the node.
 */
public static String getStrFromNode(Node xpathnode) {
    if (xpathnode.getNodeType() == Node.TEXT_NODE) {
        // we iterate over all siblings of the context node because eventually,
        // the text is "polluted" with pi's or comments
        StringBuilder sb = new StringBuilder();

        for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
            currentSibling != null;
            currentSibling = currentSibling.getNextSibling()) {
            if (currentSibling.getNodeType() == Node.TEXT_NODE) {
                sb.append(((Text) currentSibling).getData());
            }
        }

        return sb.toString();
    } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
        return ((Attr) xpathnode).getNodeValue();
    } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return ((ProcessingInstruction) xpathnode).getNodeValue();
    }

    return null;
}
 
Example 2
Project: java-tools   File: XmlTreeOperations.java   Source Code and License Vote up 5 votes
private static String getTextContent(Node node)
{
    short nodeType = node.getNodeType();
    if( nodeType == Node.ATTRIBUTE_NODE ||
        nodeType == Node.PROCESSING_INSTRUCTION_NODE ||
        nodeType == Node.COMMENT_NODE ||
        nodeType == Node.TEXT_NODE ||
        nodeType == Node.CDATA_SECTION_NODE )
    {
        return com.altova.CoreTypes.castToString(node.getNodeValue());
    }
    else
    if( nodeType == Node.DOCUMENT_NODE ||
        nodeType == Node.DOCUMENT_FRAGMENT_NODE ||
        nodeType == Node.ELEMENT_NODE ||
        nodeType == Node.ENTITY_REFERENCE_NODE )
    {
        String result = "";
        Node child = node.getFirstChild();
        for( ; child != null ; child = child.getNextSibling() )
        {
            short childNodeType = child.getNodeType();
            if( childNodeType == Node.TEXT_NODE ||
                childNodeType == Node.CDATA_SECTION_NODE ||
                childNodeType == Node.ELEMENT_NODE ||
                childNodeType == Node.ENTITY_REFERENCE_NODE )
            {
                result += getTextContent( child );
            }
        }
        return result;
    }
    else
        return "";
}
 
Example 3
Project: OpenJSharp   File: RangeImpl.java   Source Code and License Vote up 5 votes
void checkIndex(Node refNode, int offset) throws DOMException
{
    if (offset < 0) {
        throw new DOMException(
            DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
    }

    int type = refNode.getNodeType();

    // If the node contains text, ensure that the
    // offset of the range is <= to the length of the text
    if (type == Node.TEXT_NODE
        || type == Node.CDATA_SECTION_NODE
        || type == Node.COMMENT_NODE
        || type == Node.PROCESSING_INSTRUCTION_NODE) {
        if (offset > refNode.getNodeValue().length()) {
            throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
        }
    }
    else {
        // Since the node is not text, ensure that the offset
        // is valid with respect to the number of child nodes
        if (offset > refNode.getChildNodes().getLength()) {
            throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
        }
    }
}
 
Example 4
Project: OpenJSharp   File: DOM2DTM.java   Source Code and License Vote up 5 votes
/**
 * Retrieve the text content of a DOM subtree, appending it into a
 * user-supplied FastStringBuffer object. Note that attributes are
 * not considered part of the content of an element.
 * <p>
 * There are open questions regarding whitespace stripping.
 * Currently we make no special effort in that regard, since the standard
 * DOM doesn't yet provide DTD-based information to distinguish
 * whitespace-in-element-context from genuine #PCDATA. Note that we
 * should probably also consider xml:space if/when we address this.
 * DOM Level 3 may solve the problem for us.
 * <p>
 * %REVIEW% Actually, since this method operates on the DOM side of the
 * fence rather than the DTM side, it SHOULDN'T do
 * any special handling. The DOM does what the DOM does; if you want
 * DTM-level abstractions, use DTM-level methods.
 *
 * @param node Node whose subtree is to be walked, gathering the
 * contents of all Text or CDATASection nodes.
 * @param buf FastStringBuffer into which the contents of the text
 * nodes are to be concatenated.
 */
protected static void getNodeData(Node node, FastStringBuffer buf)
{

  switch (node.getNodeType())
  {
  case Node.DOCUMENT_FRAGMENT_NODE :
  case Node.DOCUMENT_NODE :
  case Node.ELEMENT_NODE :
  {
    for (Node child = node.getFirstChild(); null != child;
            child = child.getNextSibling())
    {
      getNodeData(child, buf);
    }
  }
  break;
  case Node.TEXT_NODE :
  case Node.CDATA_SECTION_NODE :
  case Node.ATTRIBUTE_NODE :  // Never a child but might be our starting node
    buf.append(node.getNodeValue());
    break;
  case Node.PROCESSING_INSTRUCTION_NODE :
    // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
    break;
  default :
    // ignore
    break;
  }
}
 
Example 5
Project: openjdk-jdk10   File: DTMNodeProxy.java   Source Code and License Vote up 5 votes
/** This is a bit of a problem in DTM, since a DTM may be a Document
 * Fragment and hence not have a clear-cut Document Element. We can
 * make it work in the well-formed cases but would that be confusing for others?
 *
 *
 * @see org.w3c.dom.Document
 */
@Override
public final Element getDocumentElement()
{
              int dochandle=dtm.getDocument();
              int elementhandle=DTM.NULL;
              for(int kidhandle=dtm.getFirstChild(dochandle);
                              kidhandle!=DTM.NULL;
                              kidhandle=dtm.getNextSibling(kidhandle))
              {
                      switch(dtm.getNodeType(kidhandle))
                      {
                      case Node.ELEMENT_NODE:
                              if(elementhandle!=DTM.NULL)
                              {
                                      elementhandle=DTM.NULL; // More than one; ill-formed.
                                      kidhandle=dtm.getLastChild(dochandle); // End loop
                              }
                              else
                                      elementhandle=kidhandle;
                              break;

                      // These are harmless; document is still wellformed
                      case Node.COMMENT_NODE:
                      case Node.PROCESSING_INSTRUCTION_NODE:
                      case Node.DOCUMENT_TYPE_NODE:
                              break;

                      default:
                              elementhandle=DTM.NULL; // ill-formed
                              kidhandle=dtm.getLastChild(dochandle); // End loop
                              break;
                      }
              }
              if(elementhandle==DTM.NULL)
                      throw new DTMDOMException(DOMException.NOT_SUPPORTED_ERR);
              else
                      return (Element)(dtm.getNode(elementhandle));
}
 
Example 6
Project: openjdk-jdk10   File: RangeImpl.java   Source Code and License Vote up 5 votes
void checkIndex(Node refNode, int offset) throws DOMException
{
    if (offset < 0) {
        throw new DOMException(
            DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
    }

    int type = refNode.getNodeType();

    // If the node contains text, ensure that the
    // offset of the range is <= to the length of the text
    if (type == Node.TEXT_NODE
        || type == Node.CDATA_SECTION_NODE
        || type == Node.COMMENT_NODE
        || type == Node.PROCESSING_INSTRUCTION_NODE) {
        if (offset > refNode.getNodeValue().length()) {
            throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
        }
    }
    else {
        // Since the node is not text, ensure that the offset
        // is valid with respect to the number of child nodes
        if (offset > refNode.getChildNodes().getLength()) {
            throw new DOMException(DOMException.INDEX_SIZE_ERR,
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null));
        }
    }
}
 
Example 7
Project: whackpad   File: XmlNode.java   Source Code and License Vote up 5 votes
static Filter PROCESSING_INSTRUCTION(final XMLName name) {
    return new Filter() {
        @Override
        boolean accept(Node node) {
            if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
                ProcessingInstruction pi = (ProcessingInstruction)node;
                return name.matchesLocalName(pi.getTarget());
            }
            return false;
        }
    };
}
 
Example 8
Project: springbootWeb   File: DomWriter.java   Source Code and License Vote up 4 votes
/**
 * Write any node.
 *
 * @param node
 *            the node
 * @throws ShellException
 *             the shell exception
 */
protected void writeAnyNode(Node node) throws ShellException {
    // is there anything to do?
    if (node == null) {
        return;
    }

    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE:
        write((Document) node);
        break;

    case Node.DOCUMENT_TYPE_NODE:
        write((DocumentType) node);
        break;

    case Node.ELEMENT_NODE:
        write((Element) node);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        write((EntityReference) node);
        break;

    case Node.CDATA_SECTION_NODE:
        write((CDATASection) node);
        break;

    case Node.TEXT_NODE:
        write((Text) node);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        write((ProcessingInstruction) node);
        break;

    case Node.COMMENT_NODE:
        write((Comment) node);
        break;

    default:
        throw new ShellException(getString(
                "RuntimeError.18", Short.toString(type))); //$NON-NLS-1$
    }
}
 
Example 9
Project: generator_mybatis   File: DomWriter.java   Source Code and License Vote up 4 votes
/**
 * Write any node.
 *
 * @param node
 *            the node
 * @throws ShellException
 *             the shell exception
 */
protected void writeAnyNode(Node node) throws ShellException {
    // is there anything to do?
    if (node == null) {
        return;
    }

    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE:
        write((Document) node);
        break;

    case Node.DOCUMENT_TYPE_NODE:
        write((DocumentType) node);
        break;

    case Node.ELEMENT_NODE:
        write((Element) node);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        write((EntityReference) node);
        break;

    case Node.CDATA_SECTION_NODE:
        write((CDATASection) node);
        break;

    case Node.TEXT_NODE:
        write((Text) node);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        write((ProcessingInstruction) node);
        break;

    case Node.COMMENT_NODE:
        write((Comment) node);
        break;

    default:
        throw new ShellException(getString(
                "RuntimeError.18", Short.toString(type))); //$NON-NLS-1$
    }
}
 
Example 10
Project: jdk8u-jdk   File: ReferenceSubTreeData.java   Source Code and License Vote up 4 votes
/**
 * Recursively traverses the subtree, and returns an XPath-equivalent
 * node-set of all nodes traversed, excluding any comment nodes,
 * if specified.
 *
 * @param node the node to traverse
 * @param nodeSet the set of nodes traversed so far
 * @param the previous sibling node
 */
@SuppressWarnings("fallthrough")
private void nodeSetMinusCommentNodes(Node node, List<Node> nodeSet,
                                      Node prevSibling)
{
    switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            nodeSet.add(node);
            NamedNodeMap attrs = node.getAttributes();
            if (attrs != null) {
                for (int i = 0, len = attrs.getLength(); i < len; i++) {
                    nodeSet.add(attrs.item(i));
                }
            }
            Node pSibling = null;
            for (Node child = node.getFirstChild(); child != null;
                child = child.getNextSibling()) {
                nodeSetMinusCommentNodes(child, nodeSet, pSibling);
                pSibling = child;
            }
            break;
        case Node.DOCUMENT_NODE :
            pSibling = null;
            for (Node child = node.getFirstChild(); child != null;
                child = child.getNextSibling()) {
                nodeSetMinusCommentNodes(child, nodeSet, pSibling);
                pSibling = child;
            }
            break;
        case Node.TEXT_NODE :
        case Node.CDATA_SECTION_NODE:
            // emulate XPath which only returns the first node in
            // contiguous text/cdata nodes
            if (prevSibling != null &&
                (prevSibling.getNodeType() == Node.TEXT_NODE ||
                 prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) {
                return;
            }
            nodeSet.add(node);
            break;
        case Node.PROCESSING_INSTRUCTION_NODE :
            nodeSet.add(node);
            break;
        case Node.COMMENT_NODE:
            if (withComments) {
                nodeSet.add(node);
            }
    }
}
 
Example 11
Project: org.mybatis.generator.core-1.3.5   File: DomWriter.java   Source Code and License Vote up 4 votes
/**
 * Write any node.
 *
 * @param node
 *            the node
 * @throws ShellException
 *             the shell exception
 */
protected void writeAnyNode(Node node) throws ShellException {
    // is there anything to do?
    if (node == null) {
        return;
    }

    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE:
        write((Document) node);
        break;

    case Node.DOCUMENT_TYPE_NODE:
        write((DocumentType) node);
        break;

    case Node.ELEMENT_NODE:
        write((Element) node);
        break;

    case Node.ENTITY_REFERENCE_NODE:
        write((EntityReference) node);
        break;

    case Node.CDATA_SECTION_NODE:
        write((CDATASection) node);
        break;

    case Node.TEXT_NODE:
        write((Text) node);
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        write((ProcessingInstruction) node);
        break;

    case Node.COMMENT_NODE:
        write((Comment) node);
        break;

    default:
        throw new ShellException(getString(
                "RuntimeError.18", Short.toString(type))); //$NON-NLS-1$
    }
}
 
Example 12
Project: convertigo-eclipse   File: TwsDomTree.java   Source Code and License Vote up 4 votes
/**
 * Adds a node in the visual tree. This method is used by the @see fillDomTree method 
 *  
 * @param parent 	the parent (Can be the tree or a parent TreeItem)
 * @param node		the node to be added
 */
public boolean addNodeInTree(Object parent, Node node, IProgressMonitor monitor) {
	TreeItem tItem = (TreeItem) parent;
	String[] values = new String[2];
	tItem.setData(node);
	// calc the node text according to the node type
	switch (node.getNodeType()) {
	case Node.ELEMENT_NODE :
		int dec = 0;
		if (node.hasAttributes()) {// add a fake first node for 'Attributes' item
			tItem.setData("dec", new Integer(dec = 1));
		}
		Node[] childs = XMLUtils.toNodeArray(node.getChildNodes());
		tItem.setData("childs", childs);
		tItem.setItemCount(childs.length + dec);
		
		values[0] = node.getNodeName();
		values[1] = getTextValue(node);
		
		tItem.setText(values);
		tItem.setImage(imageNode);
		break;
	case Node.TEXT_NODE  :
		tItem.setImage(imageText);
		tItem.setText(node.getNodeValue().trim());
		break;
	case Node.ATTRIBUTE_NODE:
		tItem.setImage(imageAttrib);
		String str = node.getNodeName() + "=\"" + node.getNodeValue() + "\"";
		tItem.setText(new String[] {str, str});
		break;
	case Node.ENTITY_NODE:
		tItem.setText("[Entity]");
		break;
	case Node.ENTITY_REFERENCE_NODE :
		tItem.setText("[Entityref]");
		break;
	case Node.PROCESSING_INSTRUCTION_NODE :
		tItem.setText("[Pi]");
		break;
	case Node.COMMENT_NODE :
		tItem.setText("[Comment]");
		break;
	case Node.DOCUMENT_FRAGMENT_NODE :
		tItem.setText("[Docfgmt]");
		break;
	case Node.DOCUMENT_TYPE_NODE :
		tItem.setText("[Doctype]");
		break;
	case Node.NOTATION_NODE :
		tItem.setText("[Notation]");
		break;
	default: break;
	}
	
	return true;
}
 
Example 13
Project: openjdk-jdk10   File: DOMValidatorHelper.java   Source Code and License Vote up 4 votes
/** 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 14
Project: openjdk-jdk10   File: FuncHere.java   Source Code and License Vote up 4 votes
@Override
public XObject execute(XPathContext xctxt) throws TransformerException {
    Node xpathOwnerNode = (Node)xctxt.getOwnerObject();
    if (xpathOwnerNode == null) {
        return null;
    }

    int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode);
    int currentNode = xctxt.getCurrentNode();
    DTM dtm = xctxt.getDTM(currentNode);
    int docContext = dtm.getDocument();

    if (docContext == DTM.NULL) {
        error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null);
    }

    // check whether currentNode and the node containing the XPath
    // expression are in the same document
    Document currentDoc = getOwnerDocument(dtm.getNode(currentNode));
    Document xpathOwnerDoc = getOwnerDocument(xpathOwnerNode);

    if (currentDoc != xpathOwnerDoc) {
        throw new TransformerException("Owner documents differ");
    }

    XNodeSet nodes = new XNodeSet(xctxt.getDTMManager());
    NodeSetDTM nodeSet = nodes.mutableNodeset();

    int hereNode = DTM.NULL;

    switch (dtm.getNodeType(xpathOwnerNodeDTM)) {

        case Node.ATTRIBUTE_NODE:
        case Node.PROCESSING_INSTRUCTION_NODE: {
            // returns a node-set containing the attribute /  processing
            // instruction node
            hereNode = xpathOwnerNodeDTM;
            nodeSet.addNode(hereNode);
            break;
        }
        case Node.TEXT_NODE : {
            // returns a node-set containing the parent element of the
            // text node that directly bears the XPath expression
            hereNode = dtm.getParent(xpathOwnerNodeDTM);
            nodeSet.addNode(hereNode);
            break;
        }
        default :
            break;
    }

    /** $todo$ Do I have to do this detach() call? */
    nodeSet.detach();

    return nodes;
}
 
Example 15
Project: OpenJSharp   File: DOM2DTM.java   Source Code and License Vote up 4 votes
/**
   * Retrieve the text content of a DOM subtree, appending it into a
   * user-supplied FastStringBuffer object. Note that attributes are
   * not considered part of the content of an element.
   * <p>
   * There are open questions regarding whitespace stripping.
   * Currently we make no special effort in that regard, since the standard
   * DOM doesn't yet provide DTD-based information to distinguish
   * whitespace-in-element-context from genuine #PCDATA. Note that we
   * should probably also consider xml:space if/when we address this.
   * DOM Level 3 may solve the problem for us.
   * <p>
   * %REVIEW% Note that as a DOM-level operation, it can be argued that this
   * routine _shouldn't_ perform any processing beyond what the DOM already
   * does, and that whitespace stripping and so on belong at the DTM level.
   * If you want a stripped DOM view, wrap DTM2DOM around DOM2DTM.
   *
   * @param node Node whose subtree is to be walked, gathering the
   * contents of all Text or CDATASection nodes.
   */
  protected static void dispatchNodeData(Node node,
                                         org.xml.sax.ContentHandler ch,
                                         int depth)
            throws org.xml.sax.SAXException
  {

    switch (node.getNodeType())
    {
    case Node.DOCUMENT_FRAGMENT_NODE :
    case Node.DOCUMENT_NODE :
    case Node.ELEMENT_NODE :
    {
      for (Node child = node.getFirstChild(); null != child;
              child = child.getNextSibling())
      {
        dispatchNodeData(child, ch, depth+1);
      }
    }
    break;
    case Node.PROCESSING_INSTRUCTION_NODE : // %REVIEW%
    case Node.COMMENT_NODE :
      if(0 != depth)
        break;
        // NOTE: Because this operation works in the DOM space, it does _not_ attempt
        // to perform Text Coalition. That should only be done in DTM space.
    case Node.TEXT_NODE :
    case Node.CDATA_SECTION_NODE :
    case Node.ATTRIBUTE_NODE :
      String str = node.getNodeValue();
      if(ch instanceof CharacterNodeHandler)
      {
        ((CharacterNodeHandler)ch).characters(node);
      }
      else
      {
        ch.characters(str.toCharArray(), 0, str.length());
      }
      break;
//    /* case Node.PROCESSING_INSTRUCTION_NODE :
//      // warning(XPATHErrorResources.WG_PARSING_AND_PREPARING);
//      break; */
    default :
      // ignore
      break;
    }
  }
 
Example 16
Project: openjdk-jdk10   File: DOMConfigurationTest.java   Source Code and License Vote up 4 votes
/**
 * 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 doc contains two subsequent processing
 * instrictions, <br>
 * <b>name</b>: canonical-form <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the subsequent processing instrictions are
 * separated with a single line break
 */
@Test
public void testCanonicalForm001() {
    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();

    Element root = doc.getDocumentElement();
    ProcessingInstruction pi1 = doc.createProcessingInstruction("target1", "data1");
    ProcessingInstruction pi2 = doc.createProcessingInstruction("target2", "data2");

    root.appendChild(pi1);
    root.appendChild(pi2);

    if (!config.canSetParameter("canonical-form", Boolean.TRUE)) {
        System.out.println("OK, setting 'canonical-form' to true is not supported");
        return;
    }

    config.setParameter("canonical-form", Boolean.TRUE);
    setHandler(doc);
    doc.normalizeDocument();

    Node child1 = root.getFirstChild();
    Node child2 = child1.getNextSibling();

    if (child2.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        Assert.fail("the second child is expected to be a" + "single line break, returned: " + child2);
    }

    // return Status.passed("OK");
}
 
Example 17
Project: OpenJSharp   File: ParentNode.java   Source Code and License Vote up 4 votes
final boolean hasTextContent(Node child) {
    return child.getNodeType() != Node.COMMENT_NODE &&
        child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE &&
        (child.getNodeType() != Node.TEXT_NODE ||
         ((TextImpl) child).isIgnorableWhitespace() == false);
}
 
Example 18
Project: openjdk-jdk10   File: AbstractDOMParser.java   Source Code and License Vote up 4 votes
/**
 * Record baseURI information for the Element (by adding xml:base attribute)
 * or for the ProcessingInstruction (by setting a baseURI field)
 * Non deferred DOM.
 *
 * @param node
 */
protected final void handleBaseURI (Node node){
    if (fDocumentImpl != null) {
        // REVISIT: remove dependency on our implementation when
        //          DOM L3 becomes REC

        String baseURI = null;
        short nodeType = node.getNodeType ();

        if (nodeType == Node.ELEMENT_NODE) {
            // if an element already has xml:base attribute
            // do nothing
            if (fNamespaceAware) {
                if (((Element)node).getAttributeNodeNS ("http://www.w3.org/XML/1998/namespace","base")!=null) {
                    return;
                }
            } else if (((Element)node).getAttributeNode ("xml:base") != null) {
                return;
            }
            // retrive the baseURI from the entity reference
            baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI ();
            if (baseURI !=null && !baseURI.equals (fDocumentImpl.getDocumentURI ())) {
                if (fNamespaceAware) {
                    ((Element)node).setAttributeNS ("http://www.w3.org/XML/1998/namespace", "xml:base", baseURI);
                } else {
                    ((Element)node).setAttribute ("xml:base", baseURI);
                }
            }
        }
        else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE) {

            baseURI = ((EntityReferenceImpl)fCurrentNode).getBaseURI ();
            if (baseURI !=null && fErrorHandler != null) {
                DOMErrorImpl error = new DOMErrorImpl ();
                error.fType = "pi-base-uri-not-preserved";
                error.fRelatedData = baseURI;
                error.fSeverity = DOMError.SEVERITY_WARNING;
                fErrorHandler.getErrorHandler ().handleError (error);
            }
        }
    }
}
 
Example 19
Project: convertigo-engine   File: TwsDomTreeWrap.java   Source Code and License Vote up 4 votes
private static void addNodeInTree2(Node node, Document document, Element parent, int [] index) {
    Element currentElement = createElement2(document, node, index);
    currentElement.setAttribute("type", Short.toString(node.getNodeType()));

    switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            currentElement.setAttribute("text", node.getNodeName());
            NamedNodeMap map = node.getAttributes();
            if (node.hasAttributes()) {
                Element attributes = createElement2(document, node, index);
                attributes.setAttribute("text", "Attributes");
                attributes.setAttribute("type", Short.toString(Node.ATTRIBUTE_NODE));
                currentElement.appendChild(attributes);

                for (int i = 0; i < map.getLength(); ++i) {
                    Element attribute = createElement2(document, map.item(i), index);
                    attribute.setAttribute("text", map.item(i).getNodeName() + "=\"" + map.item(i).getNodeValue() + "\"");
                    attribute.setAttribute("type", Short.toString(Node.ATTRIBUTE_NODE));
                    attributes.appendChild(attribute);
                }
            }
            break;

        case Node.TEXT_NODE:
            currentElement.setAttribute("text", node.getNodeValue() == null ? "" : node.getNodeValue().trim());
            break;

        case Node.ENTITY_NODE:
            currentElement.setAttribute("text", "[Entity]");
            break;

        case Node.ENTITY_REFERENCE_NODE:
            currentElement.setAttribute("text", "[Entityref]");
            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            currentElement.setAttribute("text", "[Pi]");
            break;

        case Node.COMMENT_NODE:
            currentElement.setAttribute("text", "[Comment]");
            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            currentElement.setAttribute("text", "[Docfgmt]");
            break;

        case Node.DOCUMENT_TYPE_NODE:
            currentElement.setAttribute("text", "[Doctype]");
            break;

        case Node.NOTATION_NODE:
            currentElement.setAttribute("text", "[Notation]");
            break;

        default:
            break;
    }
    parent.appendChild(currentElement);

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        addNodeInTree2(currentNode, document, currentElement, index);
    }
}
 
Example 20
Project: BiglyBT   File: SimpleXMLParserDocumentImpl.java   Source Code and License Vote up 3 votes
protected SimpleXMLParserDocumentNodeImpl[]
parseNode(
	Node		node,
	boolean		skip_this_node )
{
       int type = node.getNodeType();

	if ( (	type == Node.ELEMENT_NODE ||
			type == Node.PROCESSING_INSTRUCTION_NODE )&& !skip_this_node ){

		return( new SimpleXMLParserDocumentNodeImpl[]{ new SimpleXMLParserDocumentNodeImpl( this, node )});
	}

	Vector	v = new Vector();

       for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()){

		SimpleXMLParserDocumentNodeImpl[] kids = parseNode( child, false );

		for (int i=0;i<kids.length;i++){

			v.addElement(kids[i]);
		}
       }

	SimpleXMLParserDocumentNodeImpl[]	res = new SimpleXMLParserDocumentNodeImpl[v.size()];

	v.copyInto( res );

	return( res );
}