Connecting Tech Pros Worldwide Forums | Help | Site Map

Xpath In Javascript

Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#1: Apr 4 '07
hi all,
im using xml file its structure is lik>>
<data>
<book>
<title> </title>
<pages> </pages>
<isbn> </isbn>

</book>
</data>
-------------------------------------------------------------------------------------------------------------
now i want to use xpath and xquery like
pages>30 only thosae records to be seen
can u tell me how shld i go furhte...
im able to get whole recordset(no problem atall)
bt not able to use xpath/xquery in thiscan anyone tell me

thnxs
byeee

dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#2: Apr 4 '07

re: Xpath In Javascript


Welcome to TheScripts TSDN....

What programming language are you using? ASP, PHP, XSL...?
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#3: Apr 4 '07

re: Xpath In Javascript


Quote:

Originally Posted by dorinbogdan

Welcome to TheScripts TSDN....

What programming language are you using? ASP, PHP, XSL...?


m using JAVASCRIPT to parse the xml..
pls reply me....
thnx for reply
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#4: Apr 4 '07

re: Xpath In Javascript


You should create an XSL file an apply it on the source XML.
See this example.
The XSL should contain in a for-each loop (by book), something like:

Expand|Select|Wrap|Line Numbers
  1. <xsl:if test="pages[number(.) &gt; 30]">
  2.     <xsl:value-of select="pages" />
  3. </xsl:if>
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#5: Apr 4 '07

re: Xpath In Javascript


See also these useful examples, that don't require xsl.
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#6: Apr 4 '07

re: Xpath In Javascript


Example:
Select all books with pages>30:
Expand|Select|Wrap|Line Numbers
  1. oXMLNodeList = oXMLDoc.selectNodes("//book/pages[number(.)  &gt; 30]")
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#7: Apr 4 '07

re: Xpath In Javascript


var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("nameoffilel");

var oXMLNodeList = xmlDoc.selectNodes("//Book/Pages[<30]");
//alert(oXMLNodeList);
document.write("hello"+oXMLNodeList);


this giving nothing.....blank even not a hello...
if i remove last 3 lines then it work fine even by xmlDoc.documentElement.childNodes; im able to get all the record list
can u tell me wht is the proble
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#8: Apr 4 '07

re: Xpath In Javascript


Try this example (I could not get time to test it):
Expand|Select|Wrap|Line Numbers
  1. var oXMLNodeList = xmlDoc.selectNodes("//Book/Pages[number(.)<30]");  
  2. for( var idx = 0; idx < oXMLNodeList.length; idx++ ){
  3.     document.write("title: " + oXMLNodeList.item(idx).selectSingleNode("title").text);
  4.     document.write("   pages: " +oXMLNodeList.item(idx).selectSingleNode("pages").text);
  5.     document.write("   isbn: " +oXMLNodeList.item(idx).selectSingleNode("isbn").text);
  6. }
doss's Avatar
Newbie
 
Join Date: Mar 2007
Posts: 2
#9: Apr 4 '07

re: Xpath In Javascript


Quote:

Originally Posted by chandrashekhar maral

hi all,
im using xml file its structure is lik>>
<data>
<book>
<title> </title>
<pages> </pages>
<isbn> </isbn>

</book>
</data>
-------------------------------------------------------------------------------------------------------------
now i want to use xpath and xquery like
pages>30 only thosae records to be seen
can u tell me how shld i go furhte...
im able to get whole recordset(no problem atall)
bt not able to use xpath/xquery in thiscan anyone tell me

thnxs
byeee


May I konw what scripting language you use and what db u use ?
u can explain the problem with more understanding of the others
Thank you
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#10: Apr 4 '07

re: Xpath In Javascript


Quote:

Originally Posted by doss

May I konw what scripting language you use and what db u use ?
u can explain the problem with more understanding of the others
Thank you

Welcome to TheScripts TSDN....

It is Javascript, like the thread title says.
Please read all posts, they should answer your questions.

Thanks,
Dorin.
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#11: Apr 4 '07

re: Xpath In Javascript


thnxs for the response.....
now
1>im using Javascript......
2.>no DB as such i only want to use records which r in the xml.(for structure of xml pls see above)..
3.>now if i want to read the records from xml w/o XSLT with pages of books >30 then wht to do knw...
i used above code bt it soesnt seem to work nicely.....
can u get ....
pls tell me im just stuck ,due to which my headache started ....
so pls tell me..........
thnxs for reply
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#12: Apr 4 '07

re: Xpath In Javascript


What is the expected output result?
What problem appears now?

Thanks,
Dorin.
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#13: Apr 4 '07

re: Xpath In Javascript


Hi dorinbogdan,
Firstly thank you for all your help and being so patient with me.
Unfortunately both the code fragments did not yield the desired result... so i am taking the liberty of troubling you once again.
Lets look at it from start..
I have a XML file... its goes like this: (10-11 records here.)
[html]<?xml version="1.0" ?>
<data>
<Book>
<Title>Harry potter-1</Title>
<Pages>0</Pages>
<ISBN>158</ISBN>
</Book>
<Book>
<Title>Harry potter-2</Title>
<Pages>0</Pages>
<ISBN>158</ISBN>
</Book>
<Book>
<Title>Harry potter-3</Title>
<Pages>0</Pages>
<ISBN>158X</ISBN>
</Book>
<Book>
<Title>Harry potter-4</Title>
<Pages>0</Pages>
<ISBN>1586</ISBN>
</Book>
<Book>
<Title>Harry potter-5</Title>
<Pages>0</Pages>
<ISBN>159</ISBN>
</Book>
<Book>
<Title>Harry potter-6</Title>
<Pages>0</Pages>
<ISBN>1588</ISBN>
</Book>
<Book>
<Title>operating systems-Gelvin</Title>
<Pages>0</Pages>
<ISBN>15890</ISBN>
</Book>
<Book>
<Title>Indian culture-1</Title>
<Pages>0</Pages>
<ISBN>1586</ISBN>
</Book>
<Book>
<Title>Gandhi</Title>
<Pages>0</Pages>
<ISBN>15812</ISBN>
</Book>
<Book>
<Title>Pakistan and terrorism</Title>
<Pages>0</Pages>
<ISBN>1587</ISBN>
</Book>
<Book>
<Title>C-dac and cray computing in India</Title>
<Pages>0</Pages>
<ISBN>759</ISBN>
</Book>
</data>[/html]
When i do not use x-path (using general x-query and javascript) i get proper result... see the attached image : http://img74.imageshack.us/my.php?image=opph7.jpg

Now how do i derive the same result by using X-path in Javascript. ???
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#14: Apr 4 '07

re: Xpath In Javascript


I updated the code, however it works on IE only.
Currently, selectNodes and selectSingleNodes methods are not supported in Firefox. It is required to implement these methods manually (see this link)
Expand|Select|Wrap|Line Numbers
  1.         function loadXML()
  2.         {
  3.             var xmlDoc = null;
  4.             // code for IE
  5.             if (window.ActiveXObject)
  6.               {
  7.               xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  8.               xmlDoc.async=false;
  9.               xmlDoc.load("books.xml");
  10.               return xmlDoc;
  11.               }
  12.             // code for Mozilla, Firefox, Opera, etc.
  13.             else if (document.implementation && document.implementation.createDocument)
  14.               {
  15.               xmlDoc=document.implementation.createDocument("","",null);
  16.               xmlDoc.load("books.xml");
  17.               return xmlDoc;
  18.               }
  19.             else
  20.               {
  21.                   alert('Your browser cannot handle this script');
  22.               }
  23.         }
  24.  
  25.         function readXmlUsingXPath(){
  26.             var xmlDoc = loadXML();    
  27.             if (xmlDoc == null) {alert("XML DOM object is null");return};
  28.             var xmlNodeList = xmlDoc.selectNodes("//Book[number(Pages)<30]");
  29.             for(var idx = 0; idx < xmlNodeList.length; idx++ ){
  30.                 document.write("Title: " + xmlNodeList.item(idx).selectSingleNode("Title").text );
  31.                 document.write("   Pages: " + xmlNodeList.item(idx).selectSingleNode("Pages").text);
  32.                 document.write("   ISBN: " + xmlNodeList.item(idx).selectSingleNode("ISBN").text );
  33.                 document.write("<br />")
  34.             }
  35.         }        
  36.  
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#15: Apr 4 '07

re: Xpath In Javascript


WOW! you are fast. okay - i will test and revert
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#16: Apr 4 '07

re: Xpath In Javascript


Maybe you have seen some syntax errors in the previous code.
I corrected them there.

Thanks,
Dorin.
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#17: Apr 5 '07

re: Xpath In Javascript


excellent....
thanx dorinbogdan's
its working now in my code i think i had mistake with declration gud no...
thnx again & sorry for disturbance & als for so late reply...
can u tell me other functions/xpath used with this one...
or from whr did i get all the xquery or xpath functions......
pls tell me....
thnx buddy
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#18: Apr 5 '07

re: Xpath In Javascript


I'm regularly using W3schools tutorials.
You find almost all you need there.

The XPath functions are from there too, and other related topics.

God bless you,
Dorin.
Newbie
 
Join Date: Apr 2007
Location: pune
Posts: 19
#19: Apr 5 '07

re: Xpath In Javascript


hi and very much thanku for the all answers.....
here again now...
im using the xpath,where i want to selectthe book whose title is "indian".
so i tried this one...

var xmlNodeList = xmlDoc.selectNodes("//Book[starts-with(Title,'Indian')]");
alert(xmlNodeList.item(idx).selectSingleNode("Page s").text);

but its not working why???
thnx again for reply...
Take Care
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#20: Apr 6 '07

re: Xpath In Javascript


Try:
Expand|Select|Wrap|Line Numbers
  1. xmlDoc.setProperty("SelectionLanguage", "XPath");
  2. var xmlNodeList = xmlDoc.selectNodes("//Book[starts-with(Title,'Indian')]");
  3.  
Newbie
 
Join Date: Jun 2007
Posts: 3
#21: Jun 28 '07

re: Xpath In Javascript


I have created an ajax application which retrievs an xml file and fills in the tab fields on the form.The code works fine in IE while its does not in Mozilla. Can you please let me know if i have to install some plugins to use XPATH?

Expand|Select|Wrap|Line Numbers
  1.  
  2. <html>
  3. <head>
  4. <title>SilverLine </title>
  5. <link rel="stylesheet" href="example.css" TYPE="text/css" MEDIA="screen">
  6. <script type="text/javascript">
  7.  
  8. /* Optional: Temporarily hide the "tabber" class so it does not "flash"
  9.    on the page as plain HTML. After tabber runs, the class is changed
  10.    to "tabberlive" and it will appear.
  11. */
  12. document.write('<style type="text/css">.tabber{display:none;}<\/style>');
  13.  
  14. var tabberOptions = {
  15.  
  16.   /* Optional: instead of letting tabber run during the onload event,
  17.      we'll start it up manually. This can be useful because the onload
  18.      even runs after all the images have finished loading, and we can
  19.      run tabber at the bottom of our page to start it up faster. See the
  20.      bottom of this page for more info. Note: this variable must be set
  21.      BEFORE you include tabber.js.
  22.   */
  23.   'manualStartup':true
  24.  
  25.  };
  26.  
  27. </script>
  28.  
  29. <!-- Load the tabber code -->
  30. <script type="text/javascript" src="tabber.js"></script>
  31.  
  32. <script type="text/javascript">
  33. var request = false;
  34. function getRequestObject() { 
  35.  
  36.    if (navigator.userAgent.indexOf("MSIE")>=0) { 
  37.    var strName="Msxml2.XMLHTTP"; 
  38.       if (navigator.appVersion.indexOf("MSIE 5.5")>=0) { 
  39.          strName="Microsoft.XMLHTTP"; 
  40.    } 
  41.        try { 
  42.           objXmlHttp=new ActiveXObject(strName); 
  43.           alert ("strName"+strName);
  44.           return objXmlHttp;
  45.    } catch(e) { 
  46.          alert("Error. Scripting for ActiveX might be disabled") ;
  47.  
  48.            return; 
  49.      }  
  50.    } 
  51.    if (navigator.userAgent.indexOf("Mozilla")>=0) {
  52.       objXmlHttp=new XMLHttpRequest(); 
  53.       alert("mozilla");
  54.        return objXmlHttp; 
  55.     } 
  56.  
  57. function createDocument(){
  58.  
  59.     var aVersions = ["MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.3.0",
  60.      "MSXML2.DOMDocument","Microsoft.XmlDom"];
  61.     if (window.ActiveXObject)
  62.     {
  63.  
  64.     for(var i = 0;i<aVersions.length ; i++){
  65.  
  66.         try{
  67.  
  68.             var oXmlDom = new ActiveXObject(aVersions[i]);
  69.             //alert("returning .."+i+"  "+oXmlDom);
  70.             return oXmlDom;
  71.         }catch(oError){
  72.  
  73.         }
  74.     }
  75.     throw new Error ("MSXML  is not installed ");
  76.  
  77.     }
  78.  
  79.     else if (document.implementation && document.implementation.createDocument)
  80.     {
  81.         var xmlDoc=document.implementation.createDocument("","",null);
  82.         return xmlDoc;
  83.     }
  84.     else
  85.     {
  86.         alert ("no");
  87.         alert('Your browser cannot handle this script');
  88.     }
  89.  
  90. }
  91.  
  92. function updateTabInfo() {
  93.  
  94. if ((request.readyState == 4) && (request.status == 200)) {
  95.  
  96.     var xmlDoc = request.responseXML;
  97.     var oXmlDom = createDocument();
  98.     alert ("oxml"+oXmlDom);
  99.     oXmlDom.load(xmlDoc);
  100.     oXmlDom.setProperty("SelectionLanguage", "XPath");
  101.  
  102.     var noOfgroups  = oXmlDom.selectNodes("//user/groups/group").length;
  103.     var noOfChannels = oXmlDom.selectNodes("//user/channels/channel").length;
  104.     var noOfClouds = oXmlDom.selectNodes("//user/clouds/cloud").length;
  105.  
  106.  
  107.  
  108.     var oRoot = oXmlDom.documentElement;
  109.     var noOfChildren = oRoot.childNodes.length; //groups, channels, clouds
  110.  
  111.     var groupRoot = oRoot.childNodes[0];
  112.  
  113.     alert ("noOfgroups"+noOfgroups);
  114.     document.getElementById("group").innerHTML = noOfgroups;
  115.   }
  116.  
  117. function callServer(){
  118.  
  119.      // Build the URL to connect to
  120.  
  121.      var url = "http://localhost/user/ABC";
  122.  
  123.      request = getRequestObject();
  124.  
  125.      alert ("req"+request);
  126.      // Open a connection to the server
  127.      request.open("GET", url, true);
  128.  
  129.      // Set up a function for the server to run when it's done
  130.      request.onreadystatechange = updateTabInfo;
  131.  
  132.       // Send the request
  133.      request.send(null);
  134.  
  135.  
  136.  
  137. }
  138. </script>
  139.  
  140. </head>
  141. <body>
  142. <form name="Login" method="post" >
  143.  
  144. <div class="tabber">
  145.  
  146.  
  147.      <div class="tabbertab" id = "group">
  148.       <h2>Groups</h2>
  149.       <p>Group details.</p>
  150.      </div>
  151.  
  152.  
  153.      <div class="tabbertab" id = "channel">
  154.  
  155.       <h2>Channels</h2>
  156.       <p>Channel details.</p>
  157.      </div>
  158.  
  159.      <div class="tabbertab" id = "cloud">
  160.  
  161.       <h2>Clouds</h2>
  162.       <p>Cloud details.</p>
  163.      </div>
  164.  
  165.     <div class="tabbertab" id="trend">
  166.       <h2>Trends</h2>
  167.       <p>User details.</p>
  168.  
  169.      </div>
  170.  
  171.  
  172. </div>
  173. <script type="text/javascript">
  174.  
  175. /* Since we specified manualStartup=true, tabber will not run after
  176.    the onload event. Instead let's run it now, to prevent any delay
  177.    while images load.
  178. */
  179.  
  180. tabberAutomatic(tabberOptions);
  181.  
  182. </script>
  183. <input type="submit" name="submit" value="submit"> <br>
  184. UserName<input type="text" name="UserName" onChange="callServer();" /><br>
  185. <span id="ReturnedData"></span>
  186. </body>
  187. </html>
  188.  
  189.  
  190.  
  191.  

The XML file is
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. <?xml version = "1.0" encoding = "UTF-8"?>
  4. <user id ='ABC' name = 'BBBBB BBB'> 
  5. <groups>
  6. <group id = 'SL' name = 'SL group'>
  7.     <userlist>
  8.         <userid id ='RR' name = 'RR'/> 
  9.         <userid id ='SS' name = 'SS'/> 
  10.     </userlist>
  11. </group>
  12. <group id = 'NN' name = 'NN group'>
  13.     <userlist>
  14.     </userlist>
  15. </group>
  16. <group id = 'Web2.0' name = 'Web 2.0 Interest Group'>
  17.     <userlist>
  18.         <userid id ='SS' name = 'SSSSSS''/> 
  19.         <userid id ='NN' name = 'NNN'/> 
  20.     </userlist>
  21. </group>
  22. </groups>
  23. <channels>
  24.     <channel id ='CNN' name = 'CNN in June' url ='http://www.ibm.com/developerworks/news/dw_dwtp.rss' start='2007-06-01'/>
  25. </channels>
  26. <clouds>
  27.         <cloudid id ='cnn-in-oct' name = 'CNN in October'/>
  28.         <cloudid id ='Google-Jan' name = 'Google tags'/>
  29.         <cloudid id ='HBO-movies' name = 'HBO movie schedule'/>
  30. </clouds>
  31. </user>
  32.  
dorinbogdan's Avatar
Expert
 
Join Date: Feb 2007
Posts: 822
#22: Jun 29 '07

re: Xpath In Javascript


For Firefox, you must implement the selectNodes / selectSingleNode methods manually, see this link.
Newbie
 
Join Date: Sep 2007
Posts: 2
#23: Sep 12 '07

re: Xpath In Javascript


Hi

I am trying to load contents (from XML file using Javascript ) which needs to be displayed on HTML page on button click & upon selecting one among many from a drop down box(both button & drop down on same page). So far I have been successfull in loading the content but the problem is that the content with respect to a particular button or selection should come but in my code the whole content is getting displayed...Can u help me..its urgent..Thanx
Newbie
 
Join Date: Sep 2007
Posts: 2
#24: Sep 12 '07

re: Xpath In Javascript


The xml is like
<ab>
<xyz>
<name>A</name>
<age>22</age>
</xyz>
<xyz>
<name>B</name>
<age>23</age>
</xyz>


What i want is when i click the button for A on HTML A's data should come as o/p but what i am getting is both A's & B's.
Help required immediately
Thnx in anticipation
Reply