Jump to content

XML Parse Javascript


karthikin
 Share

Recommended Posts

Hi Guys, how can i parse the null child node? In one <CONTACT> there is no value for gmail but it another <CONTACT> it has value for gmail. How can parse these null child nodes? Please help me to parse this xml file in javascript with some code. Thanks guys...

<?xml version="1.0" encoding="UTF-8"?><CONTACTS><CONTACT><PDE-Identity>N65539</PDE-Identity><FirstName>Arun_niit</FirstName><LastName>Arun_niit</LastName><gmail/><yahoo>nura@yahoo.co.in</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65593</PDE-Identity><FirstName>Rangarajkarthik</FirstName><LastName>karthik Rangaraj</LastName><gmail>kart26@gmail.com</gmail><yahoo>karthikraj@yahoo.com</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT></CONTACTS>

Edited by karthikin
Link to comment
Share on other sites

When an element has content, you find it in element.childNodes[0].nodeValue. (I use the word element to mean the parentNode you are accessing. You will call it anything you want.)If you try that with an element that has no content, you get an error. I guess that is the problem you're asking about. The trick is to realize where the error occurs.The error does not occur when you try to reference the nodeValue.The error occurs when you try to reference the childNode.The solution is to test the length of the childNodes. If the length is 0, childNodes[0] does not exist. So don't try to reference it. Reference it only if the length is greater than 0. Something like this:

if (element.childNodes.length > 0) {   return element.childNodes[0].nodeValue;}else {   return "";}

Edited by Deirdre's Dad
Link to comment
Share on other sites

When an element has content, you find it in element.childNodes[0].nodeValue. (I use the word element to mean the parentNode you are accessing. You will call it anything you want.)If you try that with an element that has no content, you get an error. I guess that is the problem you're asking about. The trick is to realize where the error occurs.The error does not occur when you try to reference the nodeValue.The error occurs when you try to reference the childNode.The solution is to test the length of the childNodes. If the length is 0, childNodes[0] does not exist. So don't try to reference it. Reference it only if the length is greater than 0. Something like this:
function init(){var str=x[i].getElementsByTagName("PDE-Identity")[0].childNodes[0].nodeValue;document.getElementById("pde").value=str;var str=x[i].getElementsByTagName("FirstName")[0].childNodes[0].nodeValue;document.getElementById("fname").value=str; var str=x[i].getElementsByTagName("LastName")[0].childNodes[0].nodeValue;document.getElementById("lname").value=str; var str=x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue;document.getElementById("gmaail").value=str; var str=x[i].getElementsByTagName("yahoo")[0].childNodes[0].nodeValue;document.getElementById("yaahoo").value=str; var str=x[i].getElementsByTagName("alcatel-lucent")[0].childNodes[0].nodeValue;document.getElementById("alcaatel-lucent").value=str;   var str=x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;document.getElementById("facebook").value=str; var str=x[i].getElementsByTagName("Facebook-ID")[0].childNodes[0].nodeValue;document.getElementById("fid").value=str; } 

Link to comment
Share on other sites

In the code I showed you, replace element with x.getElementsByTagName("gmail")[0]That's the short answer.The better answer is to build a function using my code and pass x.getElementsByTagName("gmail")[0] to the function. This is a better answer because it will not be limited to your gmail problem. You will be able to use the function whenever you need to get a nodeValue.

Edited by Deirdre's Dad
Link to comment
Share on other sites

In the code I showed you, replace element with x.getElementsByTagName("gmail")[0]That's the short answer.The better answer is to build a function using my code and pass x.getElementsByTagName("gmail")[0] to the function. This is a better answer because it will not be limited to your gmail problem. You will be able to use the function whenever you need to get a nodeValue.
Ok. Thanks I'm gonna work on it. Thank you..
Link to comment
Share on other sites

Ok. Thanks I'm gonna work on it. Thank you..
HI, i tried in this way, it's not working.
if (x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue.childNodes.length > 0) {   return x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue.childNodes[0].nodeValue;}else {   return "";}}

I couldn't pass the output to my text box. Please help me to write the function. Thank u.

Edited by karthikin
Link to comment
Share on other sites

Add this function to your script. It should be OUTSIDE your init() function:

function get_node_value (element) {   if (element.childNodes.length > 0) {	  return element.childNodes[0].nodeValue;   }   else {	  return "";   }}

In your init() function, replace this code:

var str=x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue;

with this code:

var str = get_node_value(x[i].getElementsByTagName("gmail")[0] );

Now your problem is solved AND you have a function to use whenever you want to get the value of a text node without generating an error.

Edited by Deirdre's Dad
Link to comment
Share on other sites

HI, i tried in this way, it's not working.
if (x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue.childNodes.length > 0) {   return x[i].getElementsByTagName("gmail")[0].childNodes[0].nodeValue.childNodes[0].nodeValue;}else {   return "";}}

I couldn't pass the output to my text box. Please help me to write the function. Thank u.

Thank you it's works perfectly. I have one more problem with the dynamic menu list. I would like to have <PDE-Identity> values in my menu-list, when we select the "PDE-Identity" from menu list it should display all the values in the text box. Please explain to me how can i do this... Thanks a lot for you help and support.This is my menu-list code:
<label control="" value="Select PDE-ID:"/><menulist id="List" oncomman="">               <menupopup  id="Popup">               </menupopup></menulist> 

I found this to do the menulist but i have a hard time in understand this: https://developer.mozilla.org/en/DOM/element.getElementsByTagNameThis is the java-script:

var objNodeList = objXMLDoc.getElementsByTagName("PDE-Identity");   for (var i=0; i<objNodeList.length; i++){            var menuPopup=document.getElementById('Popup');                                      var menu1=document.createElement("menuitem");                        menu1.setAttribute("label",'objNodeList');                       menuPopup.appendChild(menu1);} var x = objXMLDoc.getElementsByTagName("CONTACT");i=-1; function init(){ var str = get_node_value(x[i].getElementsByTagName("PDE-Identity")[0] );document.getElementById("pde").value=str; var str = get_node_value(x[i].getElementsByTagName("FirstName")[0] );document.getElementById("fname").value=str;  var str = get_node_value(x[i].getElementsByTagName("LastName")[0] );document.getElementById("lname").value=str; var str = get_node_value(x[i].getElementsByTagName("gmail")[0] );document.getElementById("gmaail").value=str; var str = get_node_value(x[i].getElementsByTagName("yahoo")[0] );document.getElementById("yaahoo").value=str;  var str = get_node_value(x[i].getElementsByTagName("alcatel-lucent")[0] );document.getElementById("alcaatel-lucent").value=str;    var str = get_node_value(x[i].getElementsByTagName("URL")[0] );document.getElementById("facebook").value=str;   var str = get_node_value(x[i].getElementsByTagName("Facebook-ID")[0] );document.getElementById("fid").value=str; }function get_node_value (element) {   if (element.childNodes.length > 0) {      return element.childNodes[0].nodeValue;   }   else {      return "";   }}

code:

Edited by karthikin
Link to comment
Share on other sites

Please ask a more specific question.
I have a menu list in my XUL and how can I list all the <PDE-Identity> values in to my menu list dynamically as a menu item from XML file? If we select the menu item(PDE-Identity values=N65539) it should display the rest of the values in my text boxes. Please help me and sorry for my poor English.
<label control="" value="Select PDE-ID:"/><menulist id="menulist" oncomman="">               <menupopup  id="populate">               </menupopup></menulist>     <rows >      <row>        <label value="PDE-Identity"/>        <textbox id="pde" value=""/>      </row>      <row>        <label value="FirstName"/>        <textbox id="fname" value=""/>      </row>      <row>        <label value="LastName"/>        <textbox id="lname" value=""/>      </row>      <row>          <label value="Gmail"/>        <textbox id="gmaail" value=""/>      </row>      <row>          <label value="Yahoo"/>        <textbox id="yaahoo" value=""/>      </row>      <row>          <label value="Alcatel-Lucent"/>        <textbox id="alcaatel-lucent" value="" />      </row>      <row>          <label value="URL"/>        <textbox id="facebook" value="" />      </row>      <row>          <label value="Facebook-ID"/>        <textbox id="fid" value="" />      </row>    </rows> 

My xml code:

<?xml version="1.0" encoding="UTF-8"?><CONTACTS><CONTACT><PDE-Identity>N65539</PDE-Identity><FirstName>Arun_niit</FirstName><LastName>Arun_niit</LastName><gmail/><yahoo>nurce@yahoo.co.in</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65553</PDE-Identity><FirstName>FodenBen'</FirstName><LastName>Ben' Foden</LastName><gmail/><yahoo/><alcatel-lucent/><URL>http://www.facebook.com/profile.php?id=100002440474277</URL><Facebook-ID>100002440474277</Facebook-ID></CONTACT><CONTACT><PDE-Identity>N65565</PDE-Identity><FirstName>GhorbelMahmoud</FirstName><LastName>Mahmoud Ghorbel</LastName><gmail/><yahoo/><alcatel-lucent>mahmoud.bel@alcatel-lucent.com</alcatel-lucent><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65579</PDE-Identity><FirstName>keyankarthik</FirstName><LastName>karthik keyan</LastName><gmail/><yahoo>karthse@yahoo.co.in</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65593</PDE-Identity><FirstName>Rangarajkarthik</FirstName><LastName>karthik Rangaraj</LastName><gmail>kart2006@gmail.com</gmail><yahoo>karthrangaraj@yahoo.com</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65612</PDE-Identity><FirstName>ReddyAkky</FirstName><LastName>Akky Reddy</LastName><gmail>akkddych@gmail.com</gmail><yahoo/><alcatel-lucent/><URL/><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65626</PDE-Identity><FirstName>SandfordFrankie</FirstName><LastName>Frankie Sandford</LastName><gmail/><yahoo/><alcatel-lucent/><URL>http://www.facebook.com/FrankieSandfordApprovedPage</URL><Facebook-ID/></CONTACT><CONTACT><PDE-Identity>N65637</PDE-Identity><FirstName>TheSatsRochelle</FirstName><LastName>Rochelle TheSats</LastName><gmail/><yahoo/><alcatel-lucent/><URL>http://www.facebook.com/profile.php?id=100002487211054</URL><Facebook-ID>100002487211054</Facebook-ID></CONTACT><CONTACT><PDE-Identity>N65649</PDE-Identity><FirstName>KumarVeera</FirstName><LastName>Veera_Kumar</LastName><gmail>KUMAa81@gmail.com</gmail><yahoo>KUMag@yahoo.com</yahoo><alcatel-lucent/><URL/><Facebook-ID/></CONTACT></CONTACTS>

Link to comment
Share on other sites

This is not a specific question. It does not have many words, but the process you are describing is a big one. Please discover a small thing in your code that you do not understand. Ask about that.

Link to comment
Share on other sites

This is not a specific question. It does not have many words, but the process you are describing is a big one. Please discover a small thing in your code that you do not understand. Ask about that.
OK. I'm sorry...Here is the detailed problem....This is my menulist
<label control="" value="Select PDE-ID:"/><menulist id="menulist" oncomman="">               <menupopup  id="populate">               </menupopup></menulist> 

This is my java script:

var objNodeList = objXMLDoc.getElementsByTagName("PDE-Identity");   for (var i=0; i<objNodeList.length; i++){            var menuPopup=document.getElementById('populate');                                      var menu1=document.createElement("menuitem");                        menu1.setAttribute("label",'objNodeList');                       menuPopup.appendChild(menu1);}

Here i'm trying to get the "getElementsByTagName("PDE-Identity");" to my menu-list. I couldn't get the values of the PDE-Identity in my menu-list.Thank you.

Edited by karthikin
Link to comment
Share on other sites

If you use the function I showed you before, you can get the values of all the PDE-Identity elements like this:

val = get_node_value(objNodeList[i] );

That should go somewhere in your for-loop. I'm not sure where. Maybe here?

val = get_node_value(objNodeList[i] );menu1.setAttribute("label", val);

Link to comment
Share on other sites

Thank you for being patient with me and for your help. It works! I used you code and put it in my for loop. Like this:

var objNodeList = objXMLDoc.getElementsByTagName("PDE-Identity");   for (var i=0; i<objNodeList.length; i++){			var menuPopup=document.getElementById('populate');				val = get_node_value(objNodeList[i] );			   					 var menu1=document.createElement("menuitem");					   menu1.setAttribute("label", val);					   menuPopup.appendChild(menu1);}

Do you have any suggestion/idea to get information all the <contact> when we select the "PDE-Identity" from the menu-list? Thank you very much.

Link to comment
Share on other sites

Save yourself some work this way. After this line of code:

menu1.setAttribute("label", val);

Add this line of code:

menu1.setAttribute("myIndex", i);

myIndex is not a standard attribute. I invented it to save time. The event handler that looks at the value of the menu item's value attribute can also look at the value of the myIndex attribute. myIndex is an index of the correct CONTACT element in your XML document. You can get a reference to the correct CONTACT element like this:

var i = something.myIndex;var myContactElement = objXMLDoc.getElementsByTagName("CONTACT")[i];

You will have to replace "something" with a reference to the correct menu item. I don't know how you identify that because I can't see that part of your code.

Link to comment
Share on other sites

I'm sorry to bother you too much 'cause it's confusing to me a little bit. Please give me some more detailed information. Thank you very much.Her is my complete code, I have written this code in XUL file.

<?xml version="1.0"?><?xml-stylesheet href="chrome://global/skin/" type="text/css"?><window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" >			    <grid>	<columns>	  <column flex="1"/>	  <column flex="4"/>	   <column flex="4"/>	  <column flex="4"/>	   <column flex="4"/>	</columns> 	<rows>	  <row><label control="" value="Select PDE-ID:"/><menulist id="menulist" oncommand="display()"> >			   <menupopup  id="populate">			   </menupopup></menulist> 	  </row>	</rows></grid><groupbox>	  <label control="" accesskey="" value=""/>  <grid>	<columns>	  <column flex="1"/>	  <column flex="4"/>		<column flex="4"/>		<column flex="4"/><column flex="4"/>	</columns> 	<rows >	  <row>		<label value="PDE-Identity"/>		<textbox id="pde" value=""/>	  </row>	  <row>		<label value="FirstName"/>		<textbox id="fname" value=""/>	  </row>	  <row>		<label value="LastName"/>		<textbox id="lname" value=""/>	  </row>	  <row>		  <label value="Gmail"/>		<textbox id="gmaail" value=""/>	  </row>	  <row>		  <label value="Yahoo"/>		<textbox id="yaahoo" value=""/>	  </row>	  <row>		  <label value="Alcatel-Lucent"/>		<textbox id="alcaatel-lucent" value="" />	  </row>	  <row>		  <label value="URL"/>		<textbox id="facebook" value="" />	  </row>	  <row>		  <label value="Facebook-ID"/>		<textbox id="fid" value="" />	  </row>	</rows>  </grid><label  value=""/><grid flex="1">	<columns>		<column flex=""/>	<hbox align="center" >		<button id="previous"   label="Previous"   oncommand="previous()" />		<button id="next"	   label="Next"	   oncommand="next()"/>		<button id="save"	   label="Save"	   onclick="write()"/>		<button id="reset"	  label="Reset"	  onclick="reset()"/>		  	</hbox></columns></grid></groupbox>	  <separator/><text value="© 2011"/><separator/>  <script type="application/x-javascript"><![CDATA[    var objXMLDoc = document.implementation.createDocument('','doc',null);var objXMLHTTP = new XMLHttpRequest(); objXMLHTTP.open("GET", "file://D:/xmlparserinxul/finalversion2.xml", false);objXMLHTTP.send(null);objXMLDoc = objXMLHTTP.responseXML;	var objNodeList = objXMLDoc.getElementsByTagName("PDE-Identity");   for (var i=0; i<objNodeList.length; i++){			var menuPopup=document.getElementById('populate');				val = get_node_value(objNodeList[i] );			   					 var menu1=document.createElement("menuitem");					   menu1.setAttribute("label", val);					   menuPopup.appendChild(menu1);}function display(){} var x = objXMLDoc.getElementsByTagName("CONTACT");i=-1; function init(){ var str = get_node_value(x[i].getElementsByTagName("PDE-Identity")[0] );document.getElementById("pde").value=str; var str = get_node_value(x[i].getElementsByTagName("FirstName")[0] );document.getElementById("fname").value=str;  var str = get_node_value(x[i].getElementsByTagName("LastName")[0] );document.getElementById("lname").value=str; var str = get_node_value(x[i].getElementsByTagName("gmail")[0] );document.getElementById("gmaail").value=str; var str = get_node_value(x[i].getElementsByTagName("yahoo")[0] );document.getElementById("yaahoo").value=str;  var str = get_node_value(x[i].getElementsByTagName("alcatel-lucent")[0] );document.getElementById("alcaatel-lucent").value=str;    var str = get_node_value(x[i].getElementsByTagName("URL")[0] );document.getElementById("facebook").value=str;   var str = get_node_value(x[i].getElementsByTagName("Facebook-ID")[0] );document.getElementById("fid").value=str; }function get_node_value (element) {   if (element.childNodes.length > 0) {	  return element.childNodes[0].nodeValue;   }   else {	  return "";   }} function next(){ if (i<x.length-1)  {  i++;  init();   }} function previous(){/*document.getElementById("pde").value='';document.getElementById("fname").value='';document.getElementById("lname").value='';  document.getElementById("gmaail").value='';document.getElementById("yaahoo").value='';document.getElementById("alcaatel-lucent").value='';document.getElementById("facebook").value='';document.getElementById("fid").value=''; */ if (i>0)  {   i--;  init();   }}function reset(){document.getElementById("pde").value='';document.getElementById("fname").value='';document.getElementById("lname").value='';document.getElementById("gmaail").value='';document.getElementById("yaahoo").value='';document.getElementById("alcaatel-lucent").value='';document.getElementById("facebook").value='';document.getElementById("fid").value=''; } function save(){Components.utils.import("resource://gre/modules/NetUtil.jsm");Components.utils.import("resource://gre/modules/FileUtils.jsm"); // file is nsIFile, data is a string // You can also optionally pass a flags parameter here. It defaults to// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;var ostream = FileUtils.openSafeFileOutputStream(file) var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].				createInstance(Components.interfaces.nsIScriptableUnicodeConverter);converter.charset = "UTF-8";var istream = converter.convertToInputStream(data); // The last argument (the callback) is optional.NetUtil.asyncCopy(istream, ostream, function(status) {  if (!Components.isSuccessCode(status)) {	// Handle error!	return;  }   // Data has been written to the file.}); }  ]]></script> </window>

Edited by karthikin
Link to comment
Share on other sites

I'm sorry if i wasted your time unnecessarily. I completely forgot to include the function in the menu-list. <menulist id="menulist" oncommand="display()"> I'm started working on it. I know how to make event function in the menu-list. I'm sure i'll get back to you with the code to select menu item. I'm a slow learner and I never worked on programming much. I'm sure i'll be able to do this and I already started working on it.I'll get back to you tomorrow. Please stand by me. Thank you very much.

Edited by karthikin
Link to comment
Share on other sites

@Deirdre's Dad: I just thought that if i have more than 5O contacts in xml file using it'll be hard to display in the menu list. So i would like to have a search field to type the PDE-ID to display the contact information.

    <hbox align="center" >    <label value="Type PDE-ID to Search"/>      <textbox id="find" type="search"/>       <button label="Search" oncommand="search();"/>       <button label="Clear" oncommand="clear();"/>           </hbox>

function search(){var x = document.getElementById("find").value;alert('hi');} function clear(){document.getElementById("find").value='';}

I hope now you can assist me like the other day. This time i have learnt as much as i could. Please help me... Thank you.

Edited by karthikin
Link to comment
Share on other sites

I still think you need to master some more basics before you work on this project. I'm sorry if that seems uncaring, but this has turned into a frustrating experience for me. Maybe someone else can help you.

Link to comment
Share on other sites

I still think you need to master some more basics before you work on this project. I'm sorry if that seems uncaring, but this has turned into a frustrating experience for me. Maybe someone else can help you.
@Deirdre's Dad: You are right. I should learn basics properly. This is the first time i'm working on a real project and it's a big experience for me. I'm struggling a lot. I hope i'll be able to do it with some help.I'm sorry that I have bothered you too much. You have helped me a lot.Thank you very much. Edited by karthikin
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...