If the top-level element has a prefix associated with it, drop it.
Go recursively down and remove all prefixes. If we come across
a different prefix, throw a {@link MarshalException}...

@param doc
@throws MarshalException
505364
private static void fixupNamespace(Document doc) throws MarshalException {

		Node n;
		Element el;
		String prefix;

		n = doc.getFirstChild();

		if (n.getNodeType() != Node.ELEMENT_NODE) {
			throw new RuntimeException("No element");
		}

		el = (Element) n;

		prefix = el.getPrefix();

		if (prefix != null && prefix.length() > 0) {
			el.setPrefix(null);
		} else {
			prefix = "";
		}

		dropNamespaceDecls(el);

		removePrefixFromChildren(el, prefix);
	}
339264
function pop(doc) {
    if (doc instanceof Document) {
        _.defer(() => navigationDocument.popToDocument(doc));
    } else {
        _.defer(() => navigationDocument.popDocument());
    }
}
696870
public void endDocument() throws SAXException
  {
    super.endDocument();

    // Add a NULL entry to the end of the node arrays as
    // the end indication.
    m_exptype.addElement(NULL);
    m_parent.addElement(NULL);
    m_nextsib.addElement(NULL);
    m_firstch.addElement(NULL);

    // Set the cached references after the document is built.
    m_extendedTypes = m_expandedNameTable.getExtendedTypes();
    m_exptype_map = m_exptype.getMap();
    m_nextsib_map = m_nextsib.getMap();
    m_firstch_map = m_firstch.getMap();
    m_parent_map  = m_parent.getMap();
  }
68186
public void removeNode(int n)
  {

    if (!m_mutable)
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE, null)); //"This NodeSetDTM is not mutable!");

    this.removeElement(n);
  }
370582
private void registerPrefixIntersection(String field, String prefix,
      int start, int end,
      HashMap<String, HashSet<Integer>> docFieldAdministration) {
    if (!intersectingPrefixes.containsKey(field)) {
      intersectingPrefixes.put(field, new HashSet<String>());
    } else if (intersectingPrefixes.get(field).contains(prefix)) {
      return;
    }
    HashSet<Integer> docFieldPrefixAdministration;
    if (!docFieldAdministration.containsKey(prefix)) {
      docFieldPrefixAdministration = new HashSet<>();
      docFieldAdministration.put(prefix, docFieldPrefixAdministration);
    } else {
      docFieldPrefixAdministration = docFieldAdministration.get(prefix);
      // check
      for (int p = start; p <= end; p++) {
        if (docFieldPrefixAdministration.contains(p)) {
          intersectingPrefixes.get(field).add(prefix);
          docFieldAdministration.remove(prefix);
          return;
        }
      }
    }
    // update
    for (int p = start; p <= end; p++) {
      docFieldPrefixAdministration.add(p);
    }
  }
772797
public static boolean compare(Document d1, Document d2) throws MarshalException {
		d1.normalize();
		d2.normalize();
		return d1.isEqualNode(d2);
	}
922349
public void reload(NiceXWPFDocument doc) {
		try {
			this.close();
		} catch (IOException e) {
		    logger.error("Close failed", e);
		}
		this.doc = doc;
		this.eleTemplates = this.visitor.visitDocument(doc);
	}
1176135
@Override
    public void marshalWriter(Object graph, Writer writer, DataHolder dataHolder) throws XmlMappingException,
            IOException {
        if (graph instanceof Document) {
            OutputFormat outputFormat = OutputFormat.createCompactFormat();
            outputFormat.setSuppressDeclaration(suppressXmlDeclaration);

            XMLWriter xmlWriter = new XMLWriter(writer, outputFormat);
            try {
                xmlWriter.write((Document)graph);
            } finally {
                try {
                    xmlWriter.flush();
                } catch (Exception ex) {
                    logger.debug("Could not flush XMLWriter", ex);
                }
            }
        } else {
            if (!suppressXmlDeclaration) {
                writer.write(XML_DECLARATION);
            }

            HierarchicalStreamWriter streamWriter = new EscapingCompactWriter(writer);
            try {
                getXStream().marshal(graph, streamWriter, dataHolder);
            } catch (Exception ex) {
                throw convertXStreamException(ex, true);
            } finally {
                try {
                    streamWriter.flush();
                } catch (Exception ex) {
                    logger.debug("Could not flush HierarchicalStreamWriter", ex);
                }
            }
        }
    }
772350
public void processDocument(BufferedReader document) throws IOException {
        int docIndex = documentCounter.getAndIncrement();

        Iterator<String> documentTokens = 
            IteratorFactory.tokenizeOrdered(document);

        // As we read in the document, generate a compressed version of it,
        // which we will use during the process space method to recompute all of
        // the word vectors' semantics
        ByteArrayOutputStream compressedDocument = 
            new ByteArrayOutputStream(4096);
        DataOutputStream dos = new DataOutputStream(compressedDocument);
        int tokens = 0; // count how many are in this document
        int unfilteredTokens = 0; // how many tokens remained after filtering

        IntegerVector docVector = createVector();
        docToVector.put(docIndex, docVector);

        while (documentTokens.hasNext()) {
            tokens++;
            String focusWord = documentTokens.next();

            // If we are filtering the semantic vectors, check whether this word
            // should have its semantics calculated.  In addition, if there is a
            // filter and it would have excluded the word, do not keep its
            // semantics around
            boolean calculateSemantics =
                semanticFilter.isEmpty() || semanticFilter.contains(focusWord)
                && !focusWord.equals(IteratorFactory.EMPTY_TOKEN);

	    // If the filter does not accept this word, skip the semantic
	    // processing, continue with the next word
            if (!calculateSemantics) {
                // Do not write out any removed tokens to save space
		continue;
	    }

            // Update the occurrences of this token
            unfilteredTokens++;
            add(docVector, getTermIndexVector(focusWord));

            // Update the compress version of the document with the token.
            //
            // NOTE: this call to termToIndex *must* come after the
            // getTermIndexVector() call, which is responsible for adding this
            // mapping if it doesn't already exist.
	    int focusIndex = termToIndex.get(focusWord);

            // write the term index into the compressed for the document for
            // later corpus reprocessing
            dos.writeInt(focusIndex);
        }

        document.close();
        
        dos.close();
        byte[] docAsBytes = compressedDocument.toByteArray();

        // Once the document is finished, write the compressed contents to the
        // corpus stream
        synchronized(compressedDocumentsWriter) {
            // Write how many terms were in this document after filtering
            compressedDocumentsWriter.writeInt(unfilteredTokens);
            compressedDocumentsWriter.write(docAsBytes, 0, docAsBytes.length);
        }
    }
133805
protected void setPrefixes(final Collection<String> prefixesToSet) {
		if (prefixesToSet == null) {
			throw new IllegalArgumentException("The given prefixSet is not allowed to be null.");
		}
		final Set<String> newPrefixes = new TreeSet<String>();
		for (final String prefixString : prefixesToSet) {
			if (StringUtils.isNotBlank(prefixString)) {
				newPrefixes.add(prefixString);
			}
		}
		lock.writeLock().lock();
		try {
			prefixes = newPrefixes;
			if (getPrefix() != null && !prefixes.contains(getPrefix())) {
				defaultPrefix = null;
				localPrefix.remove();
			}
		} finally {
			lock.writeLock().unlock();
		}
	}
738109
private synchronized void appendXMLProperty(Document doc, Element conf,
	                                            String propertyName) {
		// skip writing if given property name is empty or null
		if (!Strings.isNullOrEmpty(propertyName)) {
			String value = properties.getProperty(propertyName);
			if (value != null) {
				Element propNode = doc.createElement("property");
				conf.appendChild(propNode);

				Element nameNode = doc.createElement("name");
				nameNode.appendChild(doc.createTextNode(propertyName));
				propNode.appendChild(nameNode);

				Element valueNode = doc.createElement("value");
				valueNode.appendChild(doc.createTextNode(
						properties.getProperty(propertyName)));
				propNode.appendChild(valueNode);

				Element finalNode = doc.createElement("final");
				finalNode.appendChild(doc.createTextNode(
						String.valueOf(finalParameters.contains(propertyName))));
				propNode.appendChild(finalNode);

				if (updatingResource != null) {
					String[] sources = updatingResource.get(propertyName);
					if(sources != null) {
						for(String s : sources) {
							Element sourceNode = doc.createElement("source");
							sourceNode.appendChild(doc.createTextNode(s));
							propNode.appendChild(sourceNode);
						}
					}
				}
			}
		}
	}
29213
public com.google.gwt.dom.client.Element createIFrameElement(Document doc, String name) {

        IFrameElement element = doc.createIFrameElement();
        element.setName(name);
        return element;
    }
241437
private static void copyHeader(
		final Document doc,
		final Document ndoc) {
		NodeList headnl = doc.getElementsByTagName("head");

		if (headnl.getLength() > 0) {
			Element head = (Element) headnl.item(0);
			ndoc.getDocumentElement()
					.insertBefore(ndoc.adoptNode(head.cloneNode(true)),
					ndoc.getDocumentElement().getFirstChild());
		} // end if
	}
1316580
protected synchronized void processConfDoc(Document doc) {
        Element rootElement = doc.getDocumentElement();

        if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-query-string"))) setUseQueryString(true);
        if ("true".equalsIgnoreCase(getAttrValue(rootElement, "use-context"))) {
            log.debug("use-context set to true");
            setUseContext(true);
        }
        setDecodeUsing(getAttrValue(rootElement, "decode-using"));
        setDefaultMatchType(getAttrValue(rootElement, "default-match-type"));

        NodeList rootElementList = rootElement.getChildNodes();
        for (int i = 0; i < rootElementList.getLength(); i++) {
            Node node = rootElementList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("rule")) {
                Element ruleElement = (Element) node;
                // we have a rule node
                NormalRule rule = new NormalRule();

                processRuleBasics(ruleElement, rule);
                procesConditions(ruleElement, rule);
                processRuns(ruleElement, rule);

                Node toNode = ruleElement.getElementsByTagName("to").item(0);
                rule.setTo(getNodeValue(toNode));
                rule.setToType(getAttrValue(toNode, "type"));
                rule.setToContextStr(getAttrValue(toNode, "context"));
                rule.setToLast(getAttrValue(toNode, "last"));
                rule.setQueryStringAppend(getAttrValue(toNode, "qsappend"));
                if ("true".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(true);

                processSetAttributes(ruleElement, rule);

                addRule(rule);

            } else if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("class-rule")) {
                Element ruleElement = (Element) node;

                ClassRule classRule = new ClassRule();
                if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "enabled"))) classRule.setEnabled(false);
                if ("false".equalsIgnoreCase(getAttrValue(ruleElement, "last"))) classRule.setLast(false);
                classRule.setClassStr(getAttrValue(ruleElement, "class"));
                classRule.setMethodStr(getAttrValue(ruleElement, "method"));

                addRule(classRule);

            } else if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("outbound-rule")) {

                Element ruleElement = (Element) node;
                // we have a rule node
                OutboundRule rule = new OutboundRule();

                processRuleBasics(ruleElement, rule);
                if ("true".equalsIgnoreCase(getAttrValue(ruleElement, "encodefirst"))) rule.setEncodeFirst(true);

                procesConditions(ruleElement, rule);
                processRuns(ruleElement, rule);

                Node toNode = ruleElement.getElementsByTagName("to").item(0);
                rule.setTo(getNodeValue(toNode));
                rule.setToLast(getAttrValue(toNode, "last"));
                if ("false".equalsIgnoreCase(getAttrValue(toNode, "encode"))) rule.setEncodeToUrl(false);

                processSetAttributes(ruleElement, rule);

                addOutboundRule(rule);

            } else if (node.getNodeType() == Node.ELEMENT_NODE &&
                    ((Element) node).getTagName().equals("catch")) {

                Element catchXMLElement = (Element) node;
                // we have a rule node
                CatchElem catchElem = new CatchElem();

                catchElem.setClassStr(getAttrValue(catchXMLElement, "class"));

                processRuns(catchXMLElement, catchElem);

                catchElems.add(catchElem);

            }
        }
        docProcessed = true;
    }
311951
public void setRtfDocument(RtfDocument doc) {
        super.setRtfDocument(doc);
        for(int i = 0; i < this.chunks.size(); i++) {
            ((RtfBasicElement) this.chunks.get(i)).setRtfDocument(this.document);
        }
    }
291381
public static void toSAX(Node root, SAXDelegate handler) throws SAXException{
        DOMLocator locator = new DOMLocator();

        switch(root.getNodeType()){
            case Node.DOCUMENT_NODE:
                break;
            case Node.ELEMENT_NODE:
                handler.setDocumentLocator(locator);
                handler.startDocument();
                if(root.getParentNode()!=null){
                    DOMNamespaceContext.Iterator iter = new DOMNamespaceContext.Iterator(root.getParentNode());
                    while(iter.hasNext())
                        handler.startPrefixMapping(iter.next(), iter.getNamespaceURI());
                }
                break;
            default:
                throw new IllegalArgumentException("Node must be Document or Element");
        }

        Node node = root;
        AttributesImpl attrs = new AttributesImpl();
        while(node!=null){
            locator.node = node;
            switch(node.getNodeType()){
                case Node.DOCUMENT_NODE:
                    handler.setDocumentLocator(locator);
                    handler.startDocument();
                    break;
                case Node.DOCUMENT_TYPE_NODE:
                    DocumentType docType = (DocumentType)node;
                    handler.startDTD(docType.getName(), docType.getPublicId(), docType.getSystemId());
                    break;
                case Node.ELEMENT_NODE:
                    attrs.clear();
                    NamedNodeMap nodeAttrs = node.getAttributes();
                    if(nodeAttrs!=null){
                        for(int i=nodeAttrs.getLength()-1; i>=0; i--){
                            Node attr = nodeAttrs.item(i);
                            if(XMLNS_ATTRIBUTE.equals(attr.getNodeName()))
                                handler.startPrefixMapping("", attr.getNodeValue());
                            else if(XMLNS_ATTRIBUTE.equals(attr.getPrefix()))
                                handler.startPrefixMapping(attr.getLocalName(), attr.getNodeValue());
                            else
                                attrs.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeName(), "CDATA", attr.getNodeValue());
                        }
                    }
                    handler.startElement(node.getNamespaceURI(), node.getLocalName(), node.getNodeName(), attrs);
                    break;
                case Node.TEXT_NODE:
                    char chars[] = node.getNodeValue().toCharArray();
                    handler.characters(chars, 0, chars.length);
                    break;
                case Node.CDATA_SECTION_NODE:
                    chars = node.getNodeValue().toCharArray();
                    handler.startCDATA();
                    handler.characters(chars, 0, chars.length);
                    handler.endCDATA();
                    break;
                case Node.PROCESSING_INSTRUCTION_NODE:
                    ProcessingInstruction pi = (ProcessingInstruction)node;
                    handler.processingInstruction(pi.getTarget(), pi.getData());
                    break;
                case Node.COMMENT_NODE:
                    chars = node.getNodeValue().toCharArray();
                    handler.comment(chars, 0, chars.length);
            }
            NodeList children = node.getChildNodes();
            if(children!=null && children.getLength()>0)
                node = children.item(0);
            else{
                while(true){
                    locator.node = node;
                    switch(node.getNodeType()){
                        case Node.ELEMENT_NODE:
                            handler.endElement(node.getNamespaceURI(), node.getLocalName(), node.getNodeName());
                            NamedNodeMap nodeAttrs = node.getAttributes();
                            if(nodeAttrs!=null){
                                for(int i=nodeAttrs.getLength()-1; i>=0; i--){
                                    Node attr = nodeAttrs.item(i);
                                    if(XMLNS_ATTRIBUTE.equals(attr.getNodeName()))
                                        handler.endPrefixMapping("");
                                    else if(XMLNS_ATTRIBUTE.equals(attr.getPrefix()))
                                        handler.endPrefixMapping(attr.getLocalName());
                                }
                            }
                            break;
                        case Node.DOCUMENT_TYPE_NODE:
                            handler.endDTD();
                            break;
                    }
                    if(node==root){
                        if(root.getNodeType()==Node.ELEMENT_NODE && root.getParentNode()!=null){
                            DOMNamespaceContext.Iterator iter = new DOMNamespaceContext.Iterator(root.getParentNode());
                            while(iter.hasNext())
                                handler.endPrefixMapping(iter.next());
                        }
                        handler.endDocument();
                        return;
                    }
                    if(node.getNextSibling()!=null){
                        node = node.getNextSibling();
                        break;
                    }else
                        node = node.getParentNode();
                }
            }
        }
    }
891136
public void add(DOCUMENT doc) {
      if (doc != null) {
         documents.add(doc);
         int id = documents.size() - 1;
         for (KEY key : documentMapper.apply(doc)) {
            index.put(key, id);
         }
      }
   }