473,320 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Xpath In Javascript

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
Apr 4 '07 #1
24 32508
dorinbogdan
839 Expert 512MB
Welcome to TheScripts TSDN....

What programming language are you using? ASP, PHP, XSL...?
Apr 4 '07 #2
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
Apr 4 '07 #3
dorinbogdan
839 Expert 512MB
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>
Apr 4 '07 #4
dorinbogdan
839 Expert 512MB
See also these useful examples, that don't require xsl.
Apr 4 '07 #5
dorinbogdan
839 Expert 512MB
Example:
Select all books with pages>30:
Expand|Select|Wrap|Line Numbers
  1. oXMLNodeList = oXMLDoc.selectNodes("//book/pages[number(.)  &gt; 30]")
Apr 4 '07 #6
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
Apr 4 '07 #7
dorinbogdan
839 Expert 512MB
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. }
Apr 4 '07 #8
doss
2
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
Apr 4 '07 #9
dorinbogdan
839 Expert 512MB
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.
Apr 4 '07 #10
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
Apr 4 '07 #11
dorinbogdan
839 Expert 512MB
What is the expected output result?
What problem appears now?

Thanks,
Dorin.
Apr 4 '07 #12
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. ???
Apr 4 '07 #13
dorinbogdan
839 Expert 512MB
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.  
Apr 4 '07 #14
WOW! you are fast. okay - i will test and revert
Apr 4 '07 #15
dorinbogdan
839 Expert 512MB
Maybe you have seen some syntax errors in the previous code.
I corrected them there.

Thanks,
Dorin.
Apr 4 '07 #16
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
Apr 5 '07 #17
dorinbogdan
839 Expert 512MB
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.
Apr 5 '07 #18
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
Apr 5 '07 #19
dorinbogdan
839 Expert 512MB
Try:
Expand|Select|Wrap|Line Numbers
  1. xmlDoc.setProperty("SelectionLanguage", "XPath");
  2. var xmlNodeList = xmlDoc.selectNodes("//Book[starts-with(Title,'Indian')]");
  3.  
Apr 6 '07 #20
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.  
Jun 28 '07 #21
dorinbogdan
839 Expert 512MB
For Firefox, you must implement the selectNodes / selectSingleNode methods manually, see this link.
Jun 29 '07 #22
Scion
2
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
Sep 12 '07 #23
Scion
2
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
Sep 12 '07 #24
Hallow
2
You will have issues with the namespaced XML, especially on Opera and Chrome browsers. There are also the differences from IE. In this case the you will have to make use of a library like sarisa for example. Or, could try to implement your own light xml library based on the existing implementation of the DOM on each browser. The last option it can perform faster since is based on the native browser support. I tried it my self and it behaves well until now. You can take a look here:
http://dotnetcaffe.blogspot.com
Dec 15 '09 #25

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Neil Zanella | last post by:
Hello, I would like to know whether the mozilla web browser has built in support for searching XML documents via XPath expressions as with IE's xmlobject's and xmlDoc's function selectNodes() or...
7
by: Sebastian Petzelberger | last post by:
Hi group, please give me an example of a xpath with regex or better a link with examples. Thanks in advance, Sebastian
5
by: Gnic | last post by:
Hi , I have an XmlDocument instance, I want to find a node in the xml, but I don't know it's path until runtime, for example <aaa> <bbb name="x"/> <aaa attr="y"> <ccc>sometext</ccc> </aaa>
6
by: Gale | last post by:
I'm working on something in jQuery with XPath What I want to do is: if checkbox is checked, set background color od label that contain input(checkbox) to red I have this code:...
3
by: Greg | last post by:
Hi, I want to create a web based interface that uses a form + Javascript (in an XHTML namespace) to construct an XPath to query and modify the attributes of some SVG (in an SVG namespace). ...
3
by: bruce | last post by:
for guys with python/xpath expertise.. i'm playing with xpath.. and i'm trying to solve an issue... i have the following kind of situation where i'm trying to get certain data. i have a...
4
by: Claudio Calboni | last post by:
Hello folks, I'm having some performance issues with the client-side part of my application. Basically, it renders a huge HTML table (about 20'000 cells in my testing scenario), without content....
2
by: arunairs | last post by:
Hi, Is there a way of validating and XPath? In this case , I am accepting an XPath from the user and I need to validate the XPath syntax. Is there a regular expression available that anyone can...
7
by: kaer | last post by:
I have to send an XPath request on web page with JavaScript (with XMLHttpRequest) that has to be executed before. I have no idea on how to do that. Any pointer is welcome.
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.