Convert a jsoup Document to a W3C Document.
@param in jsoup doc
@return w3c doc
497888
public Document fromJsoup(org.jsoup.nodes.Document in) {
        Validate.notNull(in);
        DocumentBuilder builder;
        try {
        	//set the factory to be namespace-aware
        	factory.setNamespaceAware(true);
            builder = factory.newDocumentBuilder();
            Document out = builder.newDocument();
            convert(in, out);
            return out;
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }
124867
protected Document responseToDoc(String response){
        Document doc = null;
        try {
            DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl();
            DocumentBuilderFactory.newInstance();
            DocumentBuilder builder =  factory.newDocumentBuilder();
            ByteArrayInputStream input =  new ByteArrayInputStream(response.getBytes("UTF-8"));
            doc = builder.parse(input);
        } catch (ParserConfigurationException e) {
            LOG.error("ParserConfigurationException", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("UnsupportedEncodingException", e);
        } catch (IOException e) {
            LOG.error("IOException", e);
        } catch (SAXException e) {
            LOG.error("SAXException", e);
        }

        return doc;
    }
759251
public static Document documentFrom(InputStream is)
            throws SAXException, IOException, ParserConfigurationException {
        is = new NamespaceRemovingInputStream(is);
        // DocumentBuilderFactory is not thread safe
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // ensure that parser writes error/warning messages to the logger
        // rather than stderr
        builder.setErrorHandler(ERROR_HANDLER);
        Document doc = builder.parse(is);
        is.close();
        return doc;
    }
500788
public static Document getSOAPMessage(InputStream in) throws Exception {
        /*
         * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while
         * ((b = in.read()) != -1) { out.write(b); }
         * 
         * System.out.println("OUT:" + out.toString());
         */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
	   // Fortify Mod: Disable entity expansion to foil External Entity Injections
	   dbf.setExpandEntityReferences(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document soapMessage = db.newDocument();
          // Fortify Mod: prevent external entity injection
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer t = tf.newTransformer();
	   // End Fortify Mod
        t.transform(new StreamSource(in), new DOMResult(soapMessage));
        return soapMessage;
    }
470417
@Override
	public SolrInputDocument convertBeanToSolrInputDocument(Object bean) {
		if (bean instanceof SolrInputDocument) {
			return (SolrInputDocument) bean;
		}

		SolrInputDocument document = new SolrInputDocument();
		getConverter().write(bean, document);
		return document;
	}
1109817
public Object read(final InputSource in) throws SAXException,
                                            IOException {
        if ( this.docFragment == null ) {
            DocumentBuilderFactory f;
            try {
                f =  DocumentBuilderFactory.newInstance();
            } catch ( FactoryConfigurationError e ) {
                // obscure JDK1.5 bug where FactoryFinder in the JRE returns a null ClassLoader, so fall back to hard coded xerces.
                // https://stg.network.org/bugzilla/show_bug.cgi?id=47169
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4633368
                try {
                    f = (DocumentBuilderFactory) Class.forName( "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" ).newInstance();
                } catch ( Exception e1 ) {
                    throw new RuntimeException( "Unable to create new DOM Document",
                                                e1 );
                }
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            // XXE protection start
            try {
                f.setFeature("http://xml.org/sax/features/external-general-entities", false);
                f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

            } catch (ParserConfigurationException e) {
                logger.warn("Unable to set parser features due to {}", e.getMessage());
            }
            // XXE protection end
            try {
                this.document = f.newDocumentBuilder().newDocument();
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            this.docFragment = this.document.createDocumentFragment();
        }

        SAXParser localParser = null;
        if ( this.parser == null ) {
            SAXParserFactory factory = null;
            try {
                factory = SAXParserFactory.newInstance();
            } catch ( FactoryConfigurationError e) {
                // obscure JDK1.5 bug where FactoryFinder in the JRE returns a null ClassLoader, so fall back to hard coded xerces.
                // https://stg.network.org/bugzilla/show_bug.cgi?id=47169
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4633368                
                try {
                    factory = (SAXParserFactory) Class.forName( "org.apache.xerces.jaxp.SAXParserFactoryImpl" ).newInstance();
                } catch ( Exception e1 ) {
                    throw new RuntimeException( "Unable to create new DOM Document",
                                                e1 );
                }
            } catch ( Exception e ) {
                throw new RuntimeException( "Unable to create new DOM Document",
                                            e );
            }
            
            factory.setNamespaceAware( true );
            // XXE protection start
            try {
                factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
                factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

            } catch (ParserConfigurationException e) {
                logger.warn("Unable to set parser features due to {}", e.getMessage());
            }
            // XXE protection end

            if ( System.getProperty( "drools.schema.validating" ) != null ) {
                this.isValidating = Boolean.getBoolean( "drools.schema.validating" );
            }

            if ( this.isValidating == true ) {
                factory.setValidating( true );
                try {
                    localParser = factory.newSAXParser();
                } catch ( final ParserConfigurationException e ) {
                    throw new RuntimeException( e.getMessage() );
                }

                try {
                    localParser.setProperty( ExtensibleXmlParser.JAXP_SCHEMA_LANGUAGE,
                                             ExtensibleXmlParser.W3C_XML_SCHEMA );
                } catch ( final SAXNotRecognizedException e ) {
                    boolean hideWarnings = Boolean.getBoolean( "drools.schema.hidewarnings" );
                    if ( !hideWarnings ) {
                        logger.warn( "Your SAX parser is not JAXP 1.2 compliant - turning off validation." );
                    }
                    localParser = null;
                }
            }

            if ( localParser == null ) {
                // not jaxp1.2 compliant so turn off validation
                try {
                    this.isValidating = false;
                    factory.setValidating( this.isValidating );
                    localParser = factory.newSAXParser();
                } catch ( final ParserConfigurationException e ) {
                    throw new RuntimeException( e.getMessage() );
                }
            }
        } else {
            localParser = this.parser;
        }

        if ( !localParser.isNamespaceAware() ) {
            throw new RuntimeException( "parser must be namespace-aware" );
        }

        localParser.parse( in,
                           this );

        return this.data;
    }
307644
function( document ){
			var newNode,
				newDocument = null;

			if( this.canCloneDocument( document )){
				newDocument = document.implementation.createHTMLDocument('');
				newNode = newDocument.importNode( document.documentElement, true );
				newDocument.replaceChild(newNode, newDocument.querySelector('html'));
			}
			return (newNode && newNode.nodeType && newNode.nodeType === 1)? newDocument : document;
		}
1139670
@SuppressWarnings("unchecked")
  private Map<String, Object> convertToMap(Object jsonDocument) {
    Map<String, Object> jsonMap = new LinkedHashMap<>();

    // Document is a text block
    if (!(jsonDocument instanceof JSONObject)) {
      jsonMap.put("content", jsonDocument);
      return jsonMap;
    }

    JSONObject obj = (JSONObject) jsonDocument;
    for (String key : obj.keySet()) {
      Object value = obj.get(key);

      if (value instanceof JSONObject) {
        value = convertToMap(value);
      } else if (value instanceof JSONArray) {
        ArrayList<Map<String, Object>> collection = new ArrayList<>();

        for (Object element : ((JSONArray) value)) {
          collection.add(convertToMap(element));
        }

        value = collection;
      }

      jsonMap.put(key, value);
    }
    return jsonMap;

  }
1100792
public static InputStream toInputStream(Document doc) throws MarshalException {

		Transformer trans;

		try {
			trans = TRANSFORMER_FACTORY.newTransformer();
		} catch (TransformerConfigurationException e) {
			IfmapJLog.error("Oh oh.... [" + e.getMessage() + "]");
			throw new MarshalException(e.getMessage());
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Result result = new StreamResult(baos);
		byte[] marshalled = null;

		doc.setXmlStandalone(true);
		Source source = new DOMSource(doc);

		try {
			trans.transform(source, result);
		} catch (TransformerException e) {
			IfmapJLog.error("Oh oh.... [" + e.getMessage() + "]");
			throw new MarshalException(e.getMessage());
		}
		try {
			baos.flush();
		} catch (IOException e) {
			IfmapJLog.error("Oh oh.... [" + e.getMessage() + "]");
			throw new MarshalException(e.getMessage());
		}

		marshalled = baos.toByteArray();

		return new ByteArrayInputStream(marshalled);
	}
876179
public static String convertDocumentToFormattedString(final Document doc, final XMLFormatProperties xmlFormatProperties,
            final boolean includeElementName) {
        return XMLUtilities.convertNodeToString(doc, includeElementName, xmlFormatProperties.getVerbatimElements(),
                xmlFormatProperties.getInlineElements(), xmlFormatProperties.getContentsInlineElements(), true);
    }
1083868
private void convertOldDocument() {

        Document newDocument = DocumentHelper.createDocument();
        Element root = newDocument.addElement(NODE_PAGES);
        root.add(I_CmsXmlSchemaType.XSI_NAMESPACE);
        root.addAttribute(I_CmsXmlSchemaType.XSI_NAMESPACE_ATTRIBUTE_NO_SCHEMA_LOCATION, XMLPAGE_XSD_SYSTEM_ID);

        Map<String, Element> pages = new HashMap<String, Element>();

        if ((m_document.getRootElement() != null) && (m_document.getRootElement().element(NODE_ELEMENTS) != null)) {
            for (Iterator<Element> i = CmsXmlGenericWrapper.elementIterator(
                m_document.getRootElement().element(NODE_ELEMENTS),
                NODE_ELEMENT); i.hasNext();) {

                Element elem = i.next();
                try {
                    String elementName = elem.attributeValue(ATTRIBUTE_NAME);
                    String elementLang = elem.attributeValue(ATTRIBUTE_LANGUAGE);
                    String elementEnabled = elem.attributeValue(ATTRIBUTE_ENABLED);
                    boolean enabled = (elementEnabled == null) ? true : Boolean.valueOf(elementEnabled).booleanValue();

                    Element page = pages.get(elementLang);
                    if (page == null) {
                        // no page available for the language, add one
                        page = root.addElement(NODE_PAGE).addAttribute(ATTRIBUTE_LANGUAGE, elementLang);
                        pages.put(elementLang, page);
                    }

                    Element newElement = page.addElement(NODE_ELEMENT).addAttribute(ATTRIBUTE_NAME, elementName);
                    if (!enabled) {
                        newElement.addAttribute(ATTRIBUTE_ENABLED, String.valueOf(enabled));
                    }
                    Element links = elem.element(NODE_LINKS);
                    if (links != null) {
                        newElement.add(links.createCopy());
                    }
                    Element content = elem.element(NODE_CONTENT);
                    if (content != null) {
                        newElement.add(content.createCopy());
                    }

                } catch (NullPointerException e) {
                    LOG.error(Messages.get().getBundle().key(Messages.ERR_XML_PAGE_CONVERT_CONTENT_0), e);
                }
            }
        }

        // now replace the old with the new document
        m_document = newDocument;
    }
611467
public static Text toText(Document doc, Object o) throws PageException {
	if (o instanceof Text) return (Text) o;
	else if (o instanceof CharacterData) return doc.createTextNode(((CharacterData) o).getData());
	return doc.createTextNode(Caster.toString(o));
    }
69443
private Document readDocument(byte[] xhtmlData) throws ParserConfigurationException, SAXException, IOException {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docbuilder = docBuilderFactory.newDocumentBuilder();
        // use special entity resolver so we don't fetch the DTDs from w3.org, which would be slow
        docbuilder.setEntityResolver(m_entityResolver);
        Document doc = docbuilder.parse(new ByteArrayInputStream(xhtmlData));
        return doc;
    }
628040
@Override
    public DocumentTranslationRequestData getDocumentTranslationRequest(
            String trId) throws ServiceException {
        if (trId == null || trId.isEmpty()) {
            throw new IllegalArgumentException("Non-empty trId must be specified.");
        }

        DocumentTranslationRequestResponse resp = invokeApiJson(
                "GET",
                escapePathSegment(account.getInstanceId()) + "/v2/doc-trs/"
                    + escapePathSegment(trId),
                null,
                DocumentTranslationRequestResponse.class);

        if (resp.getStatus() == Status.ERROR) {
            throw new ServiceException(resp.getMessage());
        }

        return new DocumentTranslationRequestDataImpl(resp.id, resp.translationRequest);
    
    }
560299
def documento(self, *args, **kwargs):
        
        forcar_unicode = kwargs.pop('forcar_unicode', False)
        incluir_xml_decl = kwargs.pop('incluir_xml_decl', True)
        doc = ET.tostring(self._xml(*args, **kwargs),
                encoding='utf-8').decode('utf-8')
        if forcar_unicode:
            if incluir_xml_decl:
                doc = u'{}\n{}'.format(constantes.XML_DECL_UNICODE, doc)
        else:
            if incluir_xml_decl:
                doc = '{}\n{}'.format(constantes.XML_DECL, unidecode(doc))
            else:
                doc = unidecode(doc)
        return doc
670615
function Document(version, encoding) {
    version = version || '1.0';
    var doc = new bindings.Document(version);
    doc.encoding(encoding || 'utf8');
    return doc;
}
910281
public String convert(String messagePayload) {
        initialize();

        // check if we already have XHTML message content
        if (messagePayload.contains(XHTML_DOCTYPE_DEFINITION)) {
            return messagePayload;
        } else {
            String xhtmlPayload;
            StringWriter xhtmlWriter = new StringWriter();
            tidyInstance.parse(new StringReader(messagePayload), xhtmlWriter);

            xhtmlPayload = xhtmlWriter.toString();
            xhtmlPayload = xhtmlPayload.replaceFirst(W3_XHTML1_URL, "org/w3/xhtml/");
            return xhtmlPayload;
        }
    }