cannot get xmlDoc to load any value. Keep getting null values - javascript

I have an xml file that I retreive via terminal emulation. I want to parse the results into a textarea in html. I am able to view the file in the textarea in xml format but have been unable to parse it into lines of the inner text.
Here is the javascript/jquery:
var x = ""
var y = ""
var Command="";
var cmd=""
$(document).ready(function() {
alert('jquery working');
$('#tester').click(function() {
$("#disptext").val("");
var APOresp = new ActiveXObject("DAT32COM.TERMINALEMULATION");
var Command = "<FORMAT>>*IA</FORMAT>";
APOresp.MakeEntry(Command);
//APOresp.GetMore(true,false);
var x = APOresp.ResponseXML;
APOresp.Close();
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(x);
$(x).find('RESPONSE').each(function() { //these lines do not work. I get null xmlDoc reference
$("#disptext").val($(this).text() + "<br />");
});
//$("#disptext").val(xmlDoc.xml); //disptext is the textarea
});
Here is what a portion of the text file looks like:
?xml version="1.0"?>
<!--This is a host terminal response-->
<RESPONSE xmlns="x-schema:C:\fp\swdir\Content\emulation-schema.xml">
<LINE INDEX="1"><![CDATA[SIGN IN ]]><CARRIAGE_RETURN/></LINE>
<LINE INDEX="2"><SOM/></LINE>
</RESPONSE>
Most files are much longer.
I want to get the text for each "LINE: tag and loop it into the textarea. It does put in the whole xml file in xml format if I use the last commented out line in the javascript file. For some unknown reason, I am unable to use the xmlDoc. I keep getting errors that the xmlDoc has null values. I have been trying to fix this for a number of days without success. Any help would be greatly appreciated.

Related

mxGraph shows grid, but does not show images

I'm using the mxGraph to develop a drawable area in a web page.
This is a legacy code and I'm trying to understand it, because the area is not showing any images besides a grid.
Here is my javascript code to show a simple diagram
//define a window to show the image and put a grid as background
container.style.background = 'url("js/src/images/grid.gif")';
//some other definitions here
var model = new mxGraphModel();
var graph = new mxGraph(container, model);
var id = _GET("id");
mxUtils.post("../Diagram",
"action=get&id="+id,
function(req)
{
var node = req.getDocumentElement();
var dec = new mxCodec(node.ownerDocument);
dec.decode(node, graph.getModel());
},
function(error){
console.log("Error in the design area");
console.log(error);
});
The ../Diagram is a servlet Java that you can see below:
try {
BufferedReader buffRead = new BufferedReader(new FileReader("/home/glassfish/mySite/Repository/"+getId()+"/"+getName()+".txt"));
String line = "";
while (true) {
if (line != null) {
file = line;
} else {
break;
}
line = buffRead.readLine();
}
buffRead.close();
} catch(Exception e) {
System.out.println("File not found");
}
return file;
The returned XML (file) is like below:
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" parent="1" style="shape=ellipse;fillColor=#33CCFF" value="Objective" vertex="1">
<mxGeometry as="geometry" height="40" width="100" x="262" y="90"/>
</mxCell>
</root>
However, the result in the screen is always the grid only
When I debug the line dec.decode(node, graph.getModel()); to see the node value I got a XML Object that contains the info returned by Java.
In Chrome I don't receive any message in the console, but when I test it in Firefox I receive an warning saying that I have a "XML parsing error in the file graph.properties", but this file is not a XML (actually, I don't know what is this file). I'm also pasting the file here
graph.properties
alreadyConnected=Nodes already connected
containsValidationErrors=Contains validation errors
updatingDocument=Updating Document. Please wait...
updatingSelection=Updating Selection. Please wait...
collapse-expand=Collapse/Expand
doubleClickOrientation=Doubleclick to change orientation
close=Close
error=Error
done=Done
cancel=Cancel
ok=OK
UPDATE
I still have not solved the problem, but I got a new evidence.
When I debug the dec.decode(node, graph.getModel()); line, I have two properties for the dec variable. A XMLDocument and also a empty array. I think that the problem could be in the encoding part, but I not found any tip in the page about mxCodec.
I finally found a solution to the problem.
The error was in the Javascript part, but I don't know why the console did not show any problem. Anyway, replace the original success function for the code below solves the problem.
function(req)
{
var doc = req.getDocumentElement();
var codec = new mxCodec(doc);
var elt = doc.firstChild;
var cells = [];
while (elt != null)
{
cells.push(codec.decode(elt));
elt = elt.nextSibling;
}
graph.addCells(cells);
}

Open file browser, select XML, parse fields using HTML/JQuery/Javascript

I'm able to launch a file-browser using an HTML Form + JQuery but am having a hard time getting past this point. New to HTML, JQuery, JS.
Essentially, I have a series of existing, empty fields on our page that, after selecting an XML from the file-browser, need to wind up populated with information, parsed from the XML.
Just looking for more open, general direction and resources, haven't been able to find much on the subject. Thanks!
Here is an example using an input type="file" element to read a selected File using XMLHttpRequest to get an XML DOM document to then populate the form elements with the data found in the XML:
function loadData(fileInput) {
var file = fileInput.files[0];
var fileURL = URL.createObjectURL(file);
var req = new XMLHttpRequest();
req.open('GET', fileURL);
req.onload = function() {
URL.revokeObjectURL(fileURL);
populateData(fileInput.form, this.responseXML);
};
req.onerror = function() {
URL.revokeObjectURL(fileURL);
console.log('Error loading XML file.');
};
req.send();
}
function populateData(form, xmlDoc) {
var root = xmlDoc.documentElement;
for (var i = 0, l = form.elements.length; i < l; i++) {
var input = form.elements[i];
if (input.name) {
var xmlElement = root.querySelector(input.name);
if (xmlElement) {
input.value = xmlElement.textContent;
}
}
}
}
<form>
<label>Select XML file to load data from:<input type="file" onchange="loadData(this);"></label>
<br>
<label>foo data
<input type="text" name="foo"></label>
<br>
<label>bar data
<input type="text" name="bar"></label>
</form>
This assumes the XML document selected is a simple XML document with a root element of any name and child elements where the element name matches the input name in the HTML form, for instance
<data>
<foo>foo data</foo>
<bar>bar data</bar>
</data>
First, You should convert xml file to JSON. There are a lot of ways to do this. You can find open source suggestions, just google it.
For example: https://code.google.com/p/x2js/.
When JSON will be got you can easy paste it into necessary fields.

Load XML data using Ajax and Javascript when XML content is received as XML file

I'm trying to display data from the xml file by first getting the content of the xml file and storing it in XML DOM. Once the DOM object is created it is then parsed. I used a for loop so as to get data from each child node of the parent node but somehow only the second node's data is showing.
This is the code where the error is:
xmlhttp.open("GET","company.xml", false); //sets the request for calling company.xml
xmlhttp.send(); //sends the request
xmlDoc = xmlhttp.responseXML; //sets and returns the content as XML DOM
//parsing the DOM object
var employeeCount = xmlDoc.getElementsByTagName("Employee");
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
The XML file:
<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<Nickname>Tania</Nickname>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>
This the output:
How can i display the data from node [0] as well? Any suggestions will be appreciated. Thanks.
The problem is that you're overwriting data from previous Employee on every iteration :
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
That's why only the last Employee data remains in innerHTMLs in the end.

Create XML in JavaScript

Is it possible to create an XML file with some data in JavaScript? I have the data stored in variables.
I've googled around a bit and it doesn't seem like it's talked about much. I thought I could use XMLWriter such as this:
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
as stated in this tutorial: EHow Tutorial
However, when I execute this code, I get the following error:
ReferenceError: XMLWriter is not defined
How can I solve this error?
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
JavaScript handles XML with 'XML DOM objects'.
You can obtain such an object in three ways:
1. Creating a new XML DOM object
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3. Parsing a string containing serialized XML
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
Note:
It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
Consider that we need to create the following XML document:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
Example
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
xml-writer(npm package)
I think this is the good way to create and write xml file easy.
Also it can be used on server side with nodejs.
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());
Simply use
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
this work for me..
var xml = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");
developer.mozilla.org/en-US/docs/Web/API/DOMParser
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
Your code is referencing this library
You can include it, and then your code in question should run as is. If you want to do this without prepending the library & build it with builtin functions only - follow answer from #Seb3736.
In Browser Example
<html>
<head>
<script src="Global.js" language="javascript"></script>
<script src="XMLWriter.js" language="javascript"></script>
<script language="javascript" type="text/javascript">
function genXML(){
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
//Do something... eg.
console.log(XML.ToString); //Yes ToString() not toString()
}
</script>
</head>
<body>
<input type="submit" value="genXML" onclick="genXML();">
</body>
</html>

is there a .innerXML?

i'd like to ask if anyone here is familiar wif xml who can give me some help...
http://www.plognow.com/xml/login.xml
and i hv a little function tht i use to break it up...
function dialogXML(varName,url){
if (window.XMLHttpRequest){
r[varName]=new XMLHttpRequest();
}else{
r[varName]=new ActiveXObject("Microsoft.XMLHTTP");
}
r[varName].onreadystatechange=function(){
if (r[varName].readyState==4 && r[varName].status==200){
var rep=r[varName].responseXML.getElementsByTagName('box')[0];
var title=rep.getElementsByTagName('title')[0].nodeValue;
var content=rep.getElementsByTagName('content')[0].nodeValue;
createDialog(title,content);
}
}
r[varName].open('GET',url,true);
r[varName].send();
}
well i'm not sure how XMLDOM works, but can i retrieve the inwards of one tag?(all the childs subchilds etc)like u'd do in innerHTML. thanks!
You can use jQuery to manipulate XML documents as well not just HTML documents. HTML documents are XML documents.
if (r[varName].readyState==4 && r[varName].status==200){
var xml = r[varName].responseXML;
var rep = $("box:first", xml);
var title = $("title:first", rep).text();
var content= $("content:first", rep).text();
createDialog(title, content);
}
If your question is how to retrieve xml tree structure then the answer is : using responseXML property of r[varName].

Categories