2017-03-15 48 views
1

我碰到下面的示例中的計算器職位的人來 -XSLT使用Java

import javax.xml.transform.*; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 
import java.io.File; 
import java.io.IOException; 
import java.net.URISyntaxException; 

public class TestMain { 
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException { 
     TransformerFactory factory = TransformerFactory.newInstance(); 
     Source xslt = new StreamSource(new File("transform.xslt")); 
     Transformer transformer = factory.newTransformer(xslt); 

     Source text = new StreamSource(new File("input.xml")); 
     transformer.transform(text, new StreamResult(new File("output.xml"))); 
    } 
} 

在上面的例子中,我想用輸入的字符串,並輸出字符串,從文件中讀取只XSLT 。是否有可能實現這一目標?

+1

的可能的複製[將字符串轉換爲在Java XML輸入流(http://stackoverflow.com/questions/1510712/convert-a-string-to- XML的輸入流中的Java) – Stobor

回答

1

有看StreamSource構造與InputStreamhttps://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamSource.html#StreamSource(java.io.InputStream)

您可以從string創建輸入這樣的:

InputStream input = new ByteArrayInputStream("<your string input>".getBytes(StandardCharsets.UTF_8)); 
    Source text = new StreamSource(input); 

,讓你的輸出string使用StringWriterStreamResult

StringWriter outputWriter = new StringWriter(); 
    StreamResult result = new StreamResult(outputWriter); 

    transformer.transform(text, result); 

    String outputAsString = outputWriter.getBuffer().toString(); 
0

我能夠做些simil AR此其提供我結果 -

import javax.xml.transform.*; 
import javax.xml.transform.stream.StreamResult; 
import javax.xml.transform.stream.StreamSource; 
import java.io.File; 
import java.io.IOException; 
import java.net.URISyntaxException; 

public class TestMain { 
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException { 
     TransformerFactory factory = TransformerFactory.newInstance(); 
     Source xslt = new StreamSource(new File("transform.xslt")); 

     Transformer transformer = factory.newTransformer(xslt); 
String xmlData = "<xml><data>test</data>"; 
InputStream stream = new ByteArrayInputStream(xmlData.getBytes(StandardCharsets.UTF_8)); 
     Source text = new StreamSource(stream); 

      StringWriter outWriter = new StringWriter(); 
      StreamResult result = new StreamResult(outWriter); 
     transformer.transform(text, result); 
      StringBuffer sb = outWriter.getBuffer(); 
      String finalstring = sb.toString(); 
    } 
}