下面列出了javax.xml.transform.Transformer#setOutputProperties ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException {
if (item.isAtomicValue()) {
out.write(item.getStringValue().getBytes(UTF8));
} else { // item is an XdmNode
XdmNode node = (XdmNode) item;
switch (node.getNodeKind()) {
case DOCUMENT:
case ELEMENT:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
final Properties props = getTransformerProperties(context);
transformer.setOutputProperties(props);
transformer.transform(node.asSource(), new StreamResult(out));
break;
default:
out.write(node.getStringValue().getBytes(UTF8));
}
}
}
void writeformattedItem(XdmItem item, ProcessContext context, OutputStream out)
throws TransformerFactoryConfigurationError, TransformerException, IOException {
if (item.isAtomicValue()) {
out.write(item.getStringValue().getBytes(UTF8));
} else { // item is an XdmNode
XdmNode node = (XdmNode) item;
switch (node.getNodeKind()) {
case DOCUMENT:
case ELEMENT:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
final Properties props = getTransformerProperties(context);
transformer.setOutputProperties(props);
transformer.transform(node.asSource(), new StreamResult(out));
break;
default:
out.write(node.getStringValue().getBytes(UTF8));
}
}
}
/**
* 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
*
* @return a Transformer encoding gb2312
*/
public static Transformer newTransformer() {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperties(properties);
return transformer;
} catch (TransformerConfigurationException tce) {
throw new RuntimeException(tce.getMessage());
}
}
/**
* Converts the Node/Element instance to XML payload.
*
* @param node the node/element instance to convert
* @return the XML payload representing the node/element
* @throws ApiException problem converting XML to string
*/
public static String childNodeToString(Node node) throws AlipayApiException {
String payload = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
tf.setOutputProperties(props);
StringWriter writer = new StringWriter();
tf.transform(new DOMSource(node), new StreamResult(writer));
payload = writer.toString();
payload = payload.replaceAll(REG_INVALID_CHARS, " ");
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return payload;
}
/**
* Converts the Node/Document/Element instance to XML payload.
*
* @param node the node/document/element instance to convert
* @return the XML payload representing the node/document/element
* @throws ApiException problem converting XML to string
*/
public static String nodeToString(Node node) throws AlipayApiException {
String payload = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.INDENT, LOGIC_YES);
props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);
tf.setOutputProperties(props);
StringWriter writer = new StringWriter();
tf.transform(new DOMSource(node), new StreamResult(writer));
payload = writer.toString();
payload = payload.replaceAll(REG_INVALID_CHARS, " ");
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return payload;
}
/**
* Transforms the XML content to XHTML/HTML format string with the XSL.
*
* @param payload the XML payload to convert
* @param xsltFile the XML stylesheet file
* @return the transformed XHTML/HTML format string
* @throws ApiException problem converting XML to HTML
*/
public static String xmlToHtml(String payload, File xsltFile)
throws AlipayApiException {
String result = null;
try {
Source template = new StreamSource(xsltFile);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(template);
Properties props = transformer.getOutputProperties();
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
transformer.setOutputProperties(props);
StreamSource source = new StreamSource(new StringReader(payload));
StreamResult sr = new StreamResult(new StringWriter());
transformer.transform(source, sr);
result = sr.getWriter().toString();
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return result;
}
/**
* Converts the Node/Document/Element instance to XML payload.
*
* @param node the node/document/element instance to convert
* @return the XML payload representing the node/document/element
* @throws AlipayApiException problem converting XML to string
*/
public static String nodeToString(Node node) throws AlipayApiException {
String payload = null;
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
Properties props = tf.getOutputProperties();
props.setProperty(OutputKeys.INDENT, LOGIC_YES);
props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);
tf.setOutputProperties(props);
StringWriter writer = new StringWriter();
tf.transform(new DOMSource(node), new StreamResult(writer));
payload = writer.toString();
payload = payload.replaceAll(REG_INVALID_CHARS, " ");
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return payload;
}
/**
* Transforms the XML content to XHTML/HTML format string with the XSL.
*
* @param payload the XML payload to convert
* @param xsltFile the XML stylesheet file
* @return the transformed XHTML/HTML format string
* @throws AlipayApiException problem converting XML to HTML
*/
public static String xmlToHtml(String payload, File xsltFile)
throws AlipayApiException {
String result = null;
try {
Source template = new StreamSource(xsltFile);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(template);
Properties props = transformer.getOutputProperties();
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);
transformer.setOutputProperties(props);
StreamSource source = new StreamSource(new StringReader(payload));
StreamResult sr = new StreamResult(new StringWriter());
transformer.transform(source, sr);
result = sr.getWriter().toString();
} catch (TransformerException e) {
throw new AlipayApiException("XML_TRANSFORM_ERROR", e);
}
return result;
}
/**
* 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。
*
* @return a Transformer encoding gb2312
*/
public static Transformer newTransformer() {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperties(properties);
return transformer;
} catch (TransformerConfigurationException tce) {
throw new RuntimeException(tce.getMessage());
}
}
public static void removeHandset(String file,String name)throws Exception{
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
FileInputStream is=new FileInputStream(file);
Document doc=dombuilder.parse(is);
NodeList devices = doc.getElementsByTagName("devices");
NodeList nodeList = doc.getElementsByTagName("device");
for(int i=0;i<nodeList.getLength();i++){
Node deviceNode = nodeList.item(i);
if(deviceNode.getTextContent().equals(name)){
devices.item(0).removeChild(deviceNode);
}
}
//save
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t=tf.newTransformer();
Properties props=t.getOutputProperties();
props.setProperty(OutputKeys.ENCODING, "GB2312");
t.setOutputProperties(props);
DOMSource dom=new DOMSource(doc);
StreamResult sr=new StreamResult(file);
t.transform(dom, sr);
}
private static void printSource(Source source) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(bos);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
Properties oprops = new Properties();
oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperties(oprops);
transformer.transform(source, sr);
System.out.println();
System.out.println("**** Response ******");
System.out.println();
System.out.println(bos.toString());
bos.close();
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Test for Transformer.setOutputProperties method.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase01() throws Exception {
String outputFile = USER_DIR + "transformer03.out";
String goldFile = GOLDEN_DIR + "transformer03GF.out";
String xsltFile = XML_DIR + "cities.xsl";
String xmlFile = XML_DIR + "cities.xml";
try (FileInputStream fis = new FileInputStream(xmlFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
Properties properties = new Properties();
properties.put("method", "xml");
properties.put("encoding", "UTF-8");
properties.put("omit-xml-declaration", "yes");
properties.put("{http://xml.apache.org/xslt}indent-amount", "0");
properties.put("indent", "no");
properties.put("standalone", "no");
properties.put("version", "1.0");
properties.put("media-type", "text/xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DOMSource domSource = new DOMSource(dbf.newDocumentBuilder().
parse(new File(xsltFile)));
Transformer transformer = TransformerFactory.newInstance().
newTransformer(domSource);
transformer.setOutputProperties(properties);
transformer.transform(new StreamSource(fis), new StreamResult(fos));
}
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Get the KeyStoreReport as XML.
*
* @return Keystore report in XML
* @throws CryptoException A crypto related problem was encountered generating the keystore report
* @throws ParserConfigurationException There was a serious problem creating the XML report
* @throws TransformerException There was a serious problem creating the XML report
*/
private String getKeyStoreReportXml()
throws CryptoException, ParserConfigurationException, TransformerException
{
StringWriter xml = new StringWriter();
Transformer tr = TF_FACTORY.newTransformer();
tr.setOutputProperties(TF_PROPS);
tr.transform(new DOMSource(generateDocument()), new StreamResult(xml));
return xml.toString();
}
private void setOutputFormat(Transformer transformer) {
Properties outFormat = new Properties();
outFormat.setProperty(INDENT, "yes");
outFormat.setProperty(METHOD, "xml");
outFormat.setProperty(OMIT_XML_DECLARATION, "no");
outFormat.setProperty(VERSION, "1.0");
outFormat.setProperty(ENCODING, UTF_8);
transformer.setOutputProperties(outFormat);
}
public static void addHandset(String file,String name,Hashtable<String,String> attri) throws Exception{
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
FileInputStream is=new FileInputStream(file);
Document doc=dombuilder.parse(is);
NodeList nodeList = doc.getElementsByTagName("devices");
if(nodeList != null && nodeList.getLength()>=1){
Node deviceNode = nodeList.item(0);
Element device = doc.createElement("device");
device.setTextContent(name);
for(Iterator itrName=attri.keySet().iterator();itrName.hasNext();){
String attriKey = (String)itrName.next();
String attriValue = (String)attri.get(attriKey);
device.setAttribute(attriKey, attriValue);
}
deviceNode.appendChild(device);
}
//save
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t=tf.newTransformer();
Properties props=t.getOutputProperties();
props.setProperty(OutputKeys.ENCODING, "GB2312");
t.setOutputProperties(props);
DOMSource dom=new DOMSource(doc);
StreamResult sr=new StreamResult(file);
t.transform(dom, sr);
}
private void printSource(Source source) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
StreamResult sr = new StreamResult(bos);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
Properties oprops = new Properties();
oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperties(oprops);
transformer.transform(source, sr);
assertEquals(bos.toString(), "<doc><response>Hello</response></doc>");
} catch (Exception e) {
e.printStackTrace();
}
}
private static String source2String(Source source) throws Exception {
final java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
final StreamResult sr = new StreamResult(bos);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
final java.util.Properties oprops = new java.util.Properties();
oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperties(oprops);
transformer.transform(source, sr);
return bos.toString();
}
/**
* Save project file
*
* @param aFile File name
* @throws javax.xml.parsers.ParserConfigurationException
*/
public void saveProjFile(String aFile) throws ParserConfigurationException {
_fileName = aFile;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("MeteoInfo");
File af = new File(aFile);
Attr fn = doc.createAttribute("File");
Attr type = doc.createAttribute("Type");
fn.setValue(af.getName());
type.setValue("projectfile");
root.setAttributeNode(fn);
root.setAttributeNode(type);
doc.appendChild(root);
//Add language element
//addLanguageElement(doc, root, Thread.CurrentThread.CurrentUICulture.Name);
//Add LayersLegend content
_mainForm.getMapDocument().getMapLayout().updateMapFrameOrder();
_mainForm.getMapDocument().exportProjectXML(doc, root, _fileName);
//Add MapLayout content
_mainForm.getMapDocument().getMapLayout().exportProjectXML(doc, root);
//Save project file
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperties(properties);
// transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//PrintWriter pw = new PrintWriter(new FileOutputStream(aFile));
FileOutputStream out = new FileOutputStream(aFile);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
} catch (TransformerException mye) {
} catch (IOException exp) {
}
}
public void write(File output, Properties outputProperties) throws TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperties(outputProperties);
StreamResult streamResult = new StreamResult(output);
transformer.transform(new DOMSource(document), streamResult);
}
/**
* Transform XML documents using XSLT with cache
*
* @param source
* The XML document content
* @param stylesheet
* The XSL source
* @param strStyleSheetId
* The StyleSheet Id
* @param params
* Parameters that can be used by the XSL StyleSheet
* @param outputProperties
* Properties to use for the XSL transform. Will overload the XSL output definition.
* @return The output document
* @throws TransformerException
* The exception
*/
public String transform( Source source, Source stylesheet, String strStyleSheetId, Map<String, String> params, Properties outputProperties )
throws TransformerException
{
Templates templates = this.getTemplates( stylesheet, strStyleSheetId );
Transformer transformer = templates.newTransformer( );
if ( outputProperties != null )
{
transformer.setOutputProperties( outputProperties );
}
if ( params != null )
{
transformer.clearParameters( );
for ( Entry<String, String> entry : params.entrySet( ) )
{
transformer.setParameter( entry.getKey( ), entry.getValue( ) );
}
}
StringWriter sw = new StringWriter( );
Result result = new StreamResult( sw );
try
{
transformer.transform( source, result );
}
catch( TransformerException e )
{
String strMessage = "strStyleSheetId = " + strStyleSheetId + " " + e.getMessage( );
if ( e.getLocationAsString( ) != null )
{
strMessage += ( " - location : " + e.getLocationAsString( ) );
}
throw new TransformerException( ERROR_MESSAGE_XLST + strMessage, e.getCause( ) );
}
finally
{
this.releaseTemplates( templates, strStyleSheetId );
}
return sw.toString( );
}