Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching XML doc thru Javascript ???

Status
Not open for further replies.

kishorkar

Programmer
Aug 12, 2003
26
IN
Hi all,

I have a XML document which has details like employee name, age, address, phone. Through my javascript i search a particular string in the XML document say the employee name and retrieve the age, address & Phone no. of that employee name. How do i do this ? Is this possible in Javascript or do we have to use ASP ? Any ready-made code available will be of great help as i need it very urgently.

Thanks and Regards,
Kishore
 
It is possible to search XML data islands through Javascript, at least in IE. Here is example:
Code:
<form name="testForm" onsubmit="submitHandler( this ); return false;">
	Last name: <input type="text" name="LastName" size="32" value="Ellison">
	<input type="submit" value="Search XML">
</form>
<xml id="XMLIsland">
	<Persons>
		<Person>
			<LastName>Gates</LastName>
			<FirstName>William</FirstName>
		</Person>
		<Person>
			<LastName>Gates</LastName>
			<FirstName>Linda</FirstName>
		</Person>
		<Person>
			<LastName>Ellison</LastName>
			<FirstName>Lawrence</FirstName>
		</Person>
	</Persons>	
</xml>

<script language="javascript">
function submitHandler( oFrm )
{	sLastName = oFrm["LastName"].value;

	if (sLastName!= "" )
	{	var oXML = document.getElementById("XMLIsland");
		var sXPathExp = "Persons/Person[LastName = \"" + sLastName + "\"]";
		var oResults = oXML.selectNodes( sXPathExp );
		
		if (oResults.length>0)
			displayResults( oResults );
		else
			alert( "No matches found." );
	}
}

function displayResults( oResults )
{	for( sMsg="", i=0; i< oResults.length; i++, sMsg += "\n")
	{	oPerson = oResults[i]
		for( j=0; j< oPerson.childNodes.length; j++ )
		{	oNode = oPerson.childNodes[j];
			sMsg += oNode.nodeName + ": " + oNode.text + "\n";
		}
	}

	alert( sMsg );
}
</script>
Basically you access XML island through DOM ID, then access XML document through XMLDocument interface (default property), then use XMLDOM methods and XPath query to filter nodes by search criteria. You can use results to transform XSLT stylesheet into (X)HTML; in example above, I only did alert().

For large result sets it is way better to generate search results server-side and populate client-side island with SRC attribute.

There is another alternative to all this stuff, by using XML.recordset stuff and data binding.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top