I have a function that returns a Document object in java - how would one go about checking whether this Document object is in JSON format or not?
Try with the following code: It will get the document object as String as then parse it to check whether it is a JSON object or a JSON array.
// IMPORTS USED
// import org.json.*;
Document doc = // YOUR DOCUMENT OBJECT;
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
try {
new JSONObject(writer.toString());
// IS JSON OBJECT
} catch(JSONException ex) {
// NOT JSON OBJECT
try {
new JSONArray(writer.toString());
// IS JSON ARRAY
} catch(JSONException ex1) {
// NOT JSON ARRAY
}
}
Related
I want to print the syncml payload in a xml file before using it. Is there a method in java to print the syncml payload into a xml file or a way to check the payload?
Solved by converting it to a string. (able to find more details from --> http://www.theserverside.com/news/thread.tss?thread_id=26060)
public void printXML(Document request){
try
{
DOMSource domSource = new DOMSource(request);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String checkpayload = writer.toString();
System.out.print(checkpayload);
}
catch(TransformerException ex)
{
ex.printStackTrace();
}
}
I have a Play web app that makes an HTTP request to a server.
The request goes well: I get a response with an 200 status code and Content-type = "application/xml".
If I print to stdout the response body, I see a well-formed Xml doc.
However, if I try to create an org.w3c.dom.XML document from the response
using WSResponse.asXml(), the method returns an empty document.
These are the relevant portions of my code:
private WSResponse sendPostRequest(String url, String body) {
WSRequest request = WS.url(url);
request.setHeader("Content-type", "application/x-www-form-urlencoded");
return request.post(body).get(5000L);
}
And:
public Result requestDefaultImport() {
String url = "some_url";
String body = "some_body";
WSResponse response = sendPostRequest(url, body);
System.out.println(response.getBody()); //prints well-formed Xml
Document xmld = response.asXml();
System.out.println(xmld); //prints: #[null document]
return ok();
}
What am I doing wrong?
Try this code:
Document doc = request().body().asXml();
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
String xmlStr = stringWriter.getBuffer().toString();
System.out.println(xmlStr);
or this if consuming from SOAP:
Document doc = soapBody.extractContentAsDocument();
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
strSoapBody = stringWriter.getBuffer().toString();
As far as I can see you are printing a string at
System.out.println(response.getBody());
However, you are printing a org.w3c.dom.Document at
System.out.println(xmld);
The solution to converting a Document to a string can be found at
How do I convert a org.w3c.dom.Document object to a String?
I have a process of XML transform in which I am writing the output transformed XML to a file. But instead of storing it in a file I want to store it in a string variable. I have created a string variable, please advise how can I store the generated XML in a string variable (msgxml instead of writing a file).
String msgxml;
System.setProperty("javax.xml.transform.TransformerFactory",
"org.apache.xalan.processor.TransformerFactoryImpl");
FileInputStream xml = new FileInputStream(xmlInput);
FileInputStream xsl = new FileInputStream(xslInput);
FileOutputStream os = new FileOutputStream(outputXmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
// Use the TransformerFactory to process the stylesheet source and produce a Transformer
StreamSource styleSource = new StreamSource(xsl);
Transformer transformer = tFactory.newTransformer(styleSource);
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(os);
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
} catch (TransformerException e) {
e.printStackTrace();
}
One way is to use an ByteArrayOutputStream instead of a FileOutputStream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tFactory = TransformerFactory.newInstance();
...
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(baos); // write to the byte array stream
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
}
...
msgxml = baos.toString("UTF-8"); // get contents of stream using UTF-8 encoding
Another solution is to use a java.io.StringWriter:
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
...
msgxml = stringWriter.toString();
I am using NekoHTML to parse contents of some HTML file..
Everything goes okay except for extracting the contents of the Document Object to some string.
I've tried uses
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
But nothing appears returned.
The problem where in Oracle App server 10.3.1.4 http://m-hewedy.blogspot.com/2011/04/oracle-application-server-overrides.html
Posible solution:
//this nekohtml
DOMParser parser = new DOMParser();
parser.parse(archivo);
//this xerces
OutputFormat format = new OutputFormat(parser.getDocument());
format.setIndenting(true);
//print xml for console
//XMLSerializer serializer = new XMLSerializer(System.out, format);
//save xml in string var
OutputStream outputStream = new ByteArrayOutputStream();
XMLSerializer serializer = new XMLSerializer(outputStream, format);
//process
serializer.serialize(parser.getDocument());
String xmlText = outputStream.toString();
System.out.println(xmlText);
//to generate a file output use fileoutputstream instead of system.out
//XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File("book.xml")), format);
Url: http://totheriver.com/learn/xml/xmltutorial.html#6.2
See e) Serialize DOM to FileOutputStream to generate the xml file "book.xml" .
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.
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();
}
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.
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);