将XML文档转换为String<br>
字符编码使用XML文档中的编码，获取不到则使用UTF-8

@param doc XML文档
@param isPretty 是否格式化输出
@return XML字符串
@since 3.0.9
509807
public static String toStr(Document doc, boolean isPretty) {
		return toStr(doc, CharsetUtil.UTF_8, isPretty);
	}
315193
protected boolean appendDocumentXmlDeclaration(StringBuilder sb, Document doc) {
        if ("1.0".equals(doc.getXmlVersion()) && doc.getXmlEncoding() == null && !doc.getXmlStandalone()) {
            // only default values => ignore
            return false;
        }
        sb.append("<?xml version=\"");
        sb.append(doc.getXmlVersion());
        sb.append("\"");
        if (doc.getXmlEncoding() != null) {
            sb.append(" encoding=\"");
            sb.append(doc.getXmlEncoding());
            sb.append("\"");
        }
        if (doc.getXmlStandalone()) {
            sb.append(" standalone=\"yes\"");
        }
        sb.append("?>");
        return true;
    }
1100213
def html_document_fromstring(s):
    
    if isinstance(s, six.text_type):
        s = s.encode('utf8')
    try:
        if html_too_big(s):
            return None

        return html5parser.document_fromstring(s, parser=_html5lib_parser())
    except Exception:
        pass
1332188
public static byte[] getDocumentToByteArray(Document dom) {
        try {
            TransformerFactory tFactory = TransformerFactory.newInstance();

            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer
                    .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.METHOD, "html");
            // TODO should be fixed to read doctype declaration
            transformer
                    .setOutputProperty(
                            OutputKeys.DOCTYPE_PUBLIC,
                            "-//W3C//DTD XHTML 1.0 Strict//EN\" "
                                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");

            DOMSource source = new DOMSource(dom);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Result result = new StreamResult(out);
            transformer.transform(source, result);

            return out.toByteArray();
        } catch (TransformerException e) {
            LOGGER.error("Error while converting the document to a byte array",
                    e);
        }
        return null;

    }
149096
private Document parseStringToDOM(String s, String encoding) {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory
          .newInstance();
      factory.setValidating(false);
      InputStream is = new ByteArrayInputStream(s.getBytes(encoding));
      Document doc = factory.newDocumentBuilder().parse(is);
      return doc;
    } catch (SAXException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Exception processing string.");
    }
    return null;
  }
793957
private static boolean isTextXml(final String mime) {
        return mime != null && (mime.equals("text/xml") || mime.equals("text/xml-external-parsed-entity") || mime.startsWith("text/") && mime.endsWith("+xml"));
    }
807468
public static String getContentByDoc(Document doc) throws Exception {
        ContentExtractor ce = new ContentExtractor(doc);
        return ce.getContentElement().text();
    }
341678
public static String escapeXML(String rawContent, String charset, boolean isNoLines) {
		if (rawContent == null)
			return "";
		else {
			StringBuffer sb = new StringBuffer();

			for (int i = 0; i < rawContent.length(); i++) {
				char ch = rawContent.charAt(i);
				if (ch == '\'')
					sb.append("&#39;");
				else if (ch == '&')
					sb.append("&amp;");
				else if (ch == '"')
					sb.append("&quot;");
				else if (ch == '<')
					sb.append("&lt;");
				else if (ch == '>')
					sb.append("&gt;");
				else if (ch > '~' && charset != null && charSetImpliesAscii(charset)) 
					// TODO - why is hashcode the only way to get the unicode number for the character
					// in jre 5.0?
					sb.append("&#x"+Integer.toHexString(ch).toUpperCase()+";");
				else if (isNoLines) {
					if (ch == '\r')
						sb.append("&#xA;");
					else if (ch != '\n')
						sb.append(ch);
				}
				else
					sb.append(ch);
			}
			return sb.toString();
		}
	}
250308
public String docToString(Document node) throws S2SException {
        try {
            DOMSource domSource = new DOMSource(node);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            return writer.toString();
        }
        catch (Exception e) {
            throw new S2SException(e.getMessage(),e);
        }
    }
1034971
def doc_strings_to_utf8(obj)
      case obj
      when ::Hash then
        {}.tap { |new_hash|
          obj.each do |key, value|
            new_hash[key] = doc_strings_to_utf8(value)
          end
        }
      when Array then
        obj.map { |item| doc_strings_to_utf8(item) }
      when String then
        if obj[0,2].unpack("C*") == [254, 255]
          utf16_to_utf8(obj)
        else
          pdfdoc_to_utf8(obj)
        end
      else
        @objects.deref(obj)
      end
    end
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);
    }
684130
static String getXmlProlog(final InputStream is, final String guessedEnc) throws IOException {
        String encoding = null;
        if (guessedEnc != null) {
            final byte[] bytes = new byte[BUFFER_SIZE];
            is.mark(BUFFER_SIZE);
            int offset = 0;
            int max = BUFFER_SIZE;
            int c = is.read(bytes, offset, max);
            int firstGT = -1;
            while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) {
                offset += c;
                max -= c;
                c = is.read(bytes, offset, max);
                firstGT = new String(bytes, 0, offset, guessedEnc).indexOf(">");
            }
            if (firstGT == -1) {
                if (c == -1) {
                    throw new IOException("Unexpected end of XML stream");
                } else {
                    throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes");
                }
            }
            final int bytesRead = offset;
            if (bytesRead > 0) {
                is.reset();
                String prolog = new String(bytes, guessedEnc).substring(0, firstGT);
                final Matcher m = ENCODING_PATTERN.matcher(prolog);
                if (m.find()) {
                    encoding = m.group(1).toUpperCase(Locale.ENGLISH);
                    encoding = encoding.substring(1, encoding.length() - 1);
                }
            }
        }
        return encoding;
    }
1096836
public static boolean isDeprecated(Doc doc) {
        if (doc.tags("deprecated").length > 0) {
            return true;
        }
        AnnotationDesc[] annotationDescList;
        if (doc instanceof PackageDoc)
            annotationDescList = ((PackageDoc)doc).annotations();
        else
            annotationDescList = ((ProgramElementDoc)doc).annotations();
        for (int i = 0; i < annotationDescList.length; i++) {
            if (annotationDescList[i].annotationType().qualifiedName().equals(
                   java.lang.Deprecated.class.getName())){
                return true;
            }
        }
        return false;
    }
1082280
public static Map<String, String> toMap(byte[] xmlBytes, String charset) throws Exception {
        SAXReader reader = new SAXReader(false);
        reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
        InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
        source.setEncoding(charset);
        Document doc = reader.read(source);
        Map<String, String> params = XmlUtils.toMap(doc.getRootElement());
        return params;
    }
320464
function isXML(res) {
  return (res.headers['content-type'] &&
          (/^[a-zA-Z]+\/xml/.test(res.headers['content-type']) ||
           /^[a-zA-Z]+\/[a-zA-Z]+\+xml/.test(res.headers['content-type'])));

}
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);
	}
1088105
def get_encodings_from_content(content):
    

    charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
    pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content))