How to 'transform' a String object (contai

2019-03-10 01:54发布

Currently, I have a String object that contains XML elements:

String carsInGarage = garage.getCars();

I now want to pass this String as an input/stream source (or some kind of source), but am unsure which one to choose and how to implement it.

Most of the solutions I have looked at import the package: javax.xml.transform and accept a XML file (stylerXML.xml) and output to a HTML file (outputFile.html) (See code below).

try 
{
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource("styler.xsl"));

    transformer.transform(new StreamSource("stylerXML.xml"), new StreamResult(new FileOutputStream("outputFile.html")));
}
catch (Exception e)
{
    e.printStackTrace();
}

I want to accept a String object and output (using XSL) to a element within an existing JSP page. I just don't know how to implement this, even having looked at the code above.

Can someone please advise/assist. I have searched high and low for a solution, but I just can't pull anything out.

标签: java xml xslt
3条回答
做自己的国王
2楼-- · 2019-03-10 01:57

Use a StringReader and a StringWriter:

try {
    StringReader reader = new StringReader("<xml>blabla</xml>");
    StringWriter writer = new StringWriter();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(
            new javax.xml.transform.stream.StreamSource("styler.xsl"));

    transformer.transform(
            new javax.xml.transform.stream.StreamSource(reader), 
            new javax.xml.transform.stream.StreamResult(writer));

    String result = writer.toString();
} catch (Exception e) {
    e.printStackTrace();
}
查看更多
时光不老,我们不散
3楼-- · 2019-03-10 02:06

If at some point you want the source to contain more than just a single string, or you don't want to generate the XML wrapper element manually, create a DOM document that contains your source and pass it to the transformer using a DOMSource.

查看更多
Explosion°爆炸
4楼-- · 2019-03-10 02:13

This worked for me.

String str = "<my>xml</my>"    
StreamSource src = new StreamSource(new StringReader(str));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result res = new StreamResult(baos);
transformer.transform(src, res);
查看更多
登录 后发表回答