I work on a web project and at this point I need to pass a hard-coded xml from Java to JavaScript to parse that xml; the problem is that I don't know exactly how to do this. As shown below, my xml is stored in a String variable, so I need to pass this variable to JavaScript.
I'm using tomcat as a server.
Java Code - that creates xml:
#Path("/getXml")
#GET
#Produces(MediaType.TEXT_XML)
#Consumes(MediaType.TEXT_PLAIN)
public String getXml(#Context HttpServletRequest request) throws TransformerConfigurationException, TransformerException{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("news-counts");
document.appendChild(rootElement);
int j=12;
for(int i=1; i<10; i++) {
Element item = document.createElement("item");
rootElement.appendChild(item);
item.setAttribute("count", "" + j);
item.setAttribute("date", "201408" + "0" + i);
j=j+2;
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String xmlOutput = writer.getBuffer().toString().replaceAll("\n|\r", "");
// return Response.status(Status.NOT_ACCEPTABLE).entity("xmlOutput").build();
//System.out.println(xmlOutput);
return xmlOutput;
} catch (ParserConfigurationException ex) {
Logger.getLogger(Searcher.class.getName()).log(Level.SEVERE, null, ex);
} finally {
return null;
}
}
JavaScript code - how I tried to acces the xmlOutput variable
function test() {
var r=new XMLHttpRequest();
r.open("GET", "http://localhost:8080/WebApplication6/tavi/searcher/getXml" , false);
r.send();
var responseText = r.responseText;
alert(responseText);
}
You can easily use Jquery for parsing xml. Heres another one Easy XML Consumption using jQuery. If you prefer pure javascript look at this thread.
Using Jquery:
var xml = $.parseXML("<news-counts><item count=\"1\" date=\"2014-08-13 00:00:00\">Stuff</item><item count=\"2\" date=\"2014-08-13 01:01:01\">Bar</item></news-counts>");
var x = xml.getElementsByTagName('item');
for(i=0;i<x.length;i++)
{
console.log(x.item(i).textContent); //Stuff Bar
console.log(x.item(i).getAttribute('count')); //1 2
console.log(x.item(i).getAttribute('date')); //2014-08-13 00:00:00 2014-08-13 01:01:01
}
Using javascript:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml("<news-counts><item count=\"1\" date='2014-08-13 00:00:00'>Stuff</item><item count=\"2\" date='2014-08-13 00:00:00'>Bar</item></news-counts>");//get attributes or contents after this line
You can parse your xml in javascript by this way -
var content = xml_string;//your xml string variable
if (typeof content == 'string') {
content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
}
You can parse xml by jQuery. Ref: http://www.jquerybyexample.net/2012/04/read-and-process-xml-using-jquery-ajax.html
Related
I'm writing a java program that is reading from a file path and creates a sitemap.xml.
The sitemap.xml will look like this
<loc>http://localhost/content/falcon/en/index/auto</loc>
<lastMod>2019-12-05</lastMod>
<changefreq>weekly</changefreq>
<priority>0.0</priority>
<testing>admin</testing>
</url>
<url>
<loc>
http://localhost/content/falcon/en/index/auto/coverage
</loc>
<lastMod>2019-09-11</lastMod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
<testing>admin</testing>
</url>
<url>
<loc>
http://localhost/content/falcon/en/index/auto/collectible
</loc>
<lastMod>2019-01-17</lastMod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
<testing>ben.snedeker#tallwave.com</testing>
</url>
<url>
<loc>
http://localhost/content/falcon/en/index/auto/collectible/features-discounts
</loc>
<lastMod>2016-12-30</lastMod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
<testing>usw8453</testing>
</url>
Inside the tags<loc> </loc>
Contains a urlthat is originally a string, depending on the url I want to be able to filter out the whole node including its siblings tags like <lastMod> <changefrequency> <priority> etc
This is the java that is writing to the xml sheet
Resource resource = resourceResolver.getResource(sitemapRootPath);
if(resource != null) {
response.setContentType("text/xml;charset=UTF-8");
Page page = resource.adaptTo(Page.class);
Iterator<Page> pageIterator = page.listChildren();
//Initializing the XML document before writing data into the file
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
LOG.info("Inside Try");
builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element rootElement = document.createElement("urlset");
rootElement.setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
document.appendChild(rootElement);
for(int i = 0; i < staticPageData.length; i ++) {
createXMLNodeForStaticPages(document, rootElement, request, staticPageData[i]);
}
while(pageIterator.hasNext()) {
createXMLNode(document, rootElement, request, pageIterator);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
out.print(xmlString);
This is the method being called by the while loop up above. It writes the xml for the children pages as well in the bottom for loop.
public void createXMLNode(Document document, Element rootElement, SlingHttpServletRequest request, Iterator<Page> pageIterator) {
Element headElement = document.createElement("url");
Element locElement = document.createElement("loc");
Element lastModElement = document.createElement("lastMod");
Element changefreqElement = document.createElement("changefreq");
Element priorityElement = document.createElement("priority");
Element testingElement = document.createElement("testing");
Node locElementNode = locElement;
Node lastModElementNode = lastModElement;
Node changefreqElementNode = changefreqElement;
Node priorityElementNode = priorityElement;
Node testingElementNode = testingElement;
Page childPage = pageIterator.next();
String location = request.getScheme() + "://" + request.getServerName() + childPage.getPath();
locElementNode.setTextContent(location);
LOG.error("childPage.getLastModified()" + childPage.getLastModified());
if(null != childPage.getLastModified()) {
Date date = childPage.getLastModified().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try {
dateFormat.parse("2019-07-15");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lastModElementNode.setTextContent(dateFormat.format(date));
}
String editor = childPage.getLastModifiedBy();
changefreqElementNode.setTextContent("weekly");
priorityElementNode.setTextContent(PriorityValue(location));
testingElementNode.setTextContent(editor);
rootElement.appendChild(headElement);
headElement.appendChild(locElementNode);
headElement.appendChild(lastModElementNode);
headElement.appendChild(changefreqElementNode);
headElement.appendChild(priorityElementNode);
headElement.appendChild(testingElementNode);
Iterator<Page> childPageIterator = childPage.listChildren();
while(childPageIterator.hasNext()) {
createXMLNode(document, rootElement, request, childPageIterator);
}
}
I want to be able to skip a whole child node when a certain string is read.
for example orignally the attribute inside a loc is just a string that is read from the file path where this java class is reading from.
String location = request.getScheme() + "://" + request.getServerName() + childPage.getPath();
locElementNode.setTextContent(location);
it gets put in a variable location then we set locElementNode with that value.
I want to be able to filter out the whole node when a reads a certain url string. The while loop should skip to the next element that is next .
Well, all you need to do is just add logic to check returned string before creating any elements and appending them
public void createXMLNode(Document document, Element rootElement, SlingHttpServletRequest request, Iterator<Page> pageIterator) {
String location = request.getScheme() + "://" + request.getServerName() + childPage.getPath();
if (location.equals("<banned url>") {
return;
}
Element headElement = document.createElement("url");
Element locElement = document.createElement("loc");
Element lastModElement = document.createElement("lastMod");
Element changefreqElement = document.createElement("changefreq");
Element priorityElement = document.createElement("priority");
Element testingElement = document.createElement("testing");
Node locElementNode = locElement;
Node lastModElementNode = lastModElement;
Node changefreqElementNode = changefreqElement;
Node priorityElementNode = priorityElement;
Node testingElementNode = testingElement;
Page childPage = pageIterator.next();
locElementNode.setTextContent(location);
....
I am parsing XML from lots of JMS messaging topics, so the structure of each message varies a lot and I'd like to make one general tool to parse them all.
To start, all I want to do is get the element names:
<gui-action>
<action>some action</action>
<params>
<param1>blue</param1>
<param2>tall</param2>
<params>
</gui-action>
I just want to retrieve the strings "gui-action", "action", "params", "param1", and "param2." Duplicates are just fine.
I've tried using org.w3c.dom.Node, Element, NodeLists and I'm not having much luck. I keep getting the element values, not the names.
private Element root;
private Document doc;
private NodeList nl;
//messageStr is passed in elsewhere in the code
//but is a string of the full XML message.
doc = xmlParse( messageStr );
root = doc.getDocumentElement();
nl = root.getChildNodes();
int size = nl.getLength();
for (int i=0; i<size; i++) {
log.info( nl.item(i).getNodeName() );
}
public Document xmlParse( String xml ){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
InputSource is;
try {
//Using factory get an instance of document builder
db = dbf.newDocumentBuilder();
is = new InputSource(new StringReader( xml ) );
doc = db.parse( is );
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
return doc;
//parse using builder to get DOM representation of the XML file
}
My logged "parsed" XML looks like this:
#text
action
#text
params
#text
Figured it out. I was iterating over only the child nodes, and not including the parent. So now I just filter out the #texts, and include the parent. Derp.
log.info(root.getNodeName() );
for (int i=0; i<size; i++) {
nodeName = nl.item(i).getNodeName();
if( nodeName != "#text" ) {
log.info( nodeName );
}
}
Now if anyone knows a way to get a NodeList of the entire document, that would be awesome.
I can't append correctly some info to my xml file. That's the scrivi function
public String scrivi (Document doc, File dest)
{
try
{
DOMSource sorgente = new DOMSource (doc);
StreamResult sr = new StreamResult (dest);
TransformerFactory tf =
TransformerFactory.newInstance();
Transformer transf = tf.newTransformer();
transf.transform (sorgente, sr);
return "Tutto ok";
}
catch (TransformerConfigurationException tce)
{
System.out.println(tce.getMessage());
return "<h1> Config </h1>";
}
catch (TransformerException te)
{
System.out.println(te.getMessage());
return "<h1> Transformer Errore </h1>";
}
}
and tath is my code:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(getClass().getResourceAsStream("/azioni.xml"));
Element root = document.getDocumentElement();
Element new_azione = document.createElement("azione");
Element id = document.createElement("id_azione");
id.setTextContent(id_azione);
Element nome = document.createElement("nome_azione");
nome.setTextContent(nome_azione);
Element prezzo_a = document.createElement("prezzo");
prezzo_a.setTextContent(prezzo);
new_azione.appendChild(id);
new_azione.appendChild(nome);
new_azione.appendChild(prezzo_a);
document.getDocumentElement().appendChild(new_azione);
String nomexmlOut="/azioni.xml";
File filedest = new File(nomexmlOut);
out.println(this.scrivi(document, filedest));
}
I get the error Transformer Errore ... how can I solve? what's Wrong?
* UPDATE *
Error Info
java.io.FileNotFoundException: /azioni.xml (Permission denied)
Hard to tell without actual exception trace or message, but my guess is that your problem is the ouput stream.
File("/azioni.xml");
is not the same as
getClass().getResourceAsStream("/azioni.xml")
Try with directing the output to system out and see if it works. i.e. declare scrivi
public String scrivi (Document doc, OutputStream out)
and call it with
scrivi(document, System.out);
UPDATE:
To write to the same file location, try something like this (untested)
File out = new File(getClasss().getResource("...").getFile());
and make sure that you close the input stream that you originally read from, before trying to write.
I am trying to send an XML file to my RESTful web server, and receive a XML file in return, however, I am getting a 500 error.
java.io.IOException: Server returned HTTP response code: 500 for URL:
http://sps-psa-240:8080/NMCJWS/rest/jmsmon2/pub at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at SendXML.send(SendXML.java:151)
at SendXML.main(SendXML.java:39)
Line 151 is InputStream response = uc.getInputStream();
If I uncomment System.out.println(((HttpURLConnection) uc).getResponseCode());,
then I get the same error on OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
I know the server works because a coworker has this working in Obj-C.
Here is my code:
public class SendXML
{
public static void main(String[] args) throws SAXException, XPathExpressionException, ParserConfigurationException,
IOException, TransformerException
{
String xml = generateXML("AC24", "/fa/gdscc/dss24-apc");
send("localhost", xml);
}
public static String generateXML(String conn, String funcAddr) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException, TransformerException
{
/*
* <?xml version="1.0" encoding="UTF-8"?>
<JMSMON2Req>
<SubItem UID="iPAD-2031e616-de74-44a7-9292-3745d2b1ba21">
<FuncAddr>/fa/gdscc/con1-ac25</FuncAddr>
<ItemName>AZANG</ItemName>
<ItemName>ELANG</ItemName>
<Metadata key="UID">iPAD-2031e616-de74-44a7-9292-3745d2b1ba21</Metadata>
<Metadata key="CONN">1</Metadata>
</SubItem>
</JMSMON2Req>
*/
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("http://sps-psa-240:8080/NMCWS/rest/conn/subsys/prof?ss=" + conn + "&pt=IPAD_DASHBOARD");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/SubscrProf/DataItem/DataItemName");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
//build xml
Document output = builder.newDocument();
//create root
org.w3c.dom.Element root = output.createElement("JMSMON2Req");
output.appendChild(root);
//create subitem
org.w3c.dom.Element subItemNode = output.createElement("SubItem");
subItemNode.setAttribute("UID", "IPAD-CN1-DSS26-SC151-PN230-AC26");
root.appendChild(subItemNode);
//create funcAddr
org.w3c.dom.Element funcAddrNode = output.createElement("FuncAddr");
Text text = output.createTextNode(funcAddr);
funcAddrNode.appendChild(text);
subItemNode.appendChild(funcAddrNode);
//create itemname
for (int i = 0; i < nodes.getLength(); i++)
{
org.w3c.dom.Element itemNameNode = output.createElement("SubItem");
text = output.createTextNode(nodes.item(i).getTextContent());
itemNameNode.appendChild(text);
subItemNode.appendChild(itemNameNode);
}
//create metadata uid
org.w3c.dom.Element metaDataNode = output.createElement("Metadata");
metaDataNode.setAttribute("key", "UID");
text = output.createTextNode("IPAD-CN1-DSS26-SC151-PN230-AC26");
metaDataNode.appendChild(text);
subItemNode.appendChild(metaDataNode);
//create metadata conn
org.w3c.dom.Element metaDataNode2 = output.createElement("Metadata");
metaDataNode2.setAttribute("key", "CONN");
text = output.createTextNode("4");
metaDataNode2.appendChild(text);
subItemNode.appendChild(metaDataNode2);
/////////////////
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult out = new StreamResult(sw);
DOMSource source = new DOMSource(output);
trans.transform(source, out);
String xmlString = sw.toString();
//print xml
System.out.println("Here's the xml:\n" + xmlString);
return xmlString;
}
public static void send(String urladdress, String file) throws MalformedURLException, IOException
{
String charset = "UTF-8";
String s = URLEncoder.encode(file, charset);
// Open the connection and prepare to POST
URLConnection uc = new URL(urladdress).openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Accept-Charset", charset);
uc.setRequestProperty("Content-Type","text/xml");
try
{
//System.out.println(((HttpURLConnection) uc).getResponseCode());
OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
out.write(s);
out.flush();
InputStream response = uc.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(response));
String line;
while ((line = r.readLine()) != null)
System.out.println(line);
out.close();
response.close();
}
catch (IOException e)
{
e.printStackTrace(); // should do real exception handling
}
}
}
I figured out my problem. I had to encode xmlString in UTF-8
Look at the logs on the server. What is causing the 500 error?
Is this a RESTful web service, or a SOAP web service you're submitting to?
Consider using some sort of XML<->Object framework like JAXB or XStream.
Consider using some sort of RESTful web service framework like Jersey or RestEasy.
Consider using some sort of SOAP framework like JAX-WS or Apache Axis
Make sure you are using the right encoding.
URLEncoder.encode is making the content safe for transfer as 'application/x-www-form-urlencoded', but you probably want to use UTF-8.
Also, new OutputStreamWriter(...) should specify the desired encoding. You are currently using the standard platform encoding which is probably iso-8859-1.
Third, don't try to mess around with URLConnection yourself, if there are plenty of libs around there, that can make you life easier.
Here is the send method done in Resty (Disclaimer: I'm the author of it). HTTPClient is another choice to consider as are other client-side libraries.
import us.monoid.web.Resty;
import static us.monoid.web.Resty.*;
Resty r = new Resty();
String result = r.text(urladdress, new Content("text/xml", file.getBytes("UTF-8"))).toString();
So I'm trying to create an xml document in my android application. I'm using the code that I used when writing a java application. I tried as shown below:
public void createxml() throws SAXException, IOException {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "images" + File.separator + "newxml.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
// root elements
// Document doc = docBuilder.newDocument();
// Element rootElement = doc.get
// doc.appendChild(rootElement);
Node node = doc.getDocumentElement();
// staff elements
Element outfit = doc.createElement("outfit");
node.appendChild(outfit);
// set attribute to staff element
/*
* Attr attr = doc.createAttribute("id"); attr.setValue("1");
* staff.setAttributeNode(attr);
*/
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
if (savename.equals("none")) {
} else {
Element nameelement = doc.createElement("name");
nameelement.appendChild(doc.createTextNode(savename));
outfit.appendChild(nameelement);
}
if (hatloc.equals("none")) {
} else {
Element hatelement = doc.createElement("hat");
hatelement.appendChild(doc.createTextNode(hatloc));
outfit.appendChild(hatelement);
}
if (shirtloc.equals("none")) {
} else {
Element shirtelement = doc.createElement("shirt");
shirtelement.appendChild(doc.createTextNode(shirtloc));
outfit.appendChild(shirtelement);
}
if (pantloc.equals("none")) {
} else {
Element pantselement = doc.createElement("pants");
pantselement.appendChild(doc.createTextNode(pantloc));
outfit.appendChild(pantselement);
}
if (shoeloc.equals("none")) {
} else {
Element shoeselement = doc.createElement("shoes");
shoeselement.appendChild(doc.createTextNode(shoeloc));
outfit.appendChild(shoeselement);
}
if (acc1loc.equals("none")) {
} else {
Element accelement = doc.createElement("accessories");
accelement.appendChild(doc.createTextNode(acc1loc));
outfit.appendChild(accelement);
}
if (acc2loc.equals("none")) {
} else {
Element acc2element = doc.createElement("accessories2");
acc2element.appendChild(doc.createTextNode(acc2loc));
outfit.appendChild(acc2element);
}
if (beltloc.equals("none")) {
} else {
Element beltelement = doc.createElement("belt");
beltelement.appendChild(doc.createTextNode(beltloc));
outfit.appendChild(beltelement);
}
if (dressloc.equals("none")) {
} else {
Element dresselement = doc.createElement("dress");
dresselement.appendChild(doc.createTextNode(dressloc));
outfit.appendChild(dresselement);
}
if (jacketloc.equals("none")) {
} else {
Element jacketelement = doc.createElement("jacket");
jacketelement.appendChild(doc.createTextNode(jacketloc));
outfit.appendChild(jacketelement);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
new File(Environment.getExternalStorageDirectory()
+ File.separator + "images" + File.separator
+ "newxml.xml"));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
hatloc = "none";
shirtloc = "none";
pantloc = "none";
shoeloc = "none";
acc1loc = "none";
acc2loc = "none";
beltloc = "none";
dressloc = "none";
jacketloc = "none";
savename = "none";
}
Everything worked fine until I got to this section below. I think it's the section where the xml file i created gets written. Does anyone know of a way to do this that works in android?
The code breaks with the TransformerFactory, Transformer, DOMSource, StreamResult and TransformerException.
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(
new File(Environment.getExternalStorageDirectory() + File.separator
+ "images" + File.separator + "newxml.xml"));
transformer.transform(source, result);
I think that the Transfomer class is not included in the Android API you're using.
To avoid using Transformer you should manually iterate over your xml tree, otherwise you can rely on some external libraries. You should take a look here.