Jump to content

Open, Edit And Save Xml


Recommended Posts

Hi,I was going through your tutorial onhttp://www.w3schools.com/xsl/xsl_editxml.aspwhich has tool.xml

<?xml version="1.0" encoding="ISO-8859-1"?><tool>  <field id="prodName">	<value>HAMMER HG2606</value>  </field>  <field id="prodNo">	<value>32456240</value>  </field>  <field id="price">	<value>$30.00</value>  </field></tool>

tool.xsl

<?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/">  <html>  <body>  <form method="post" action="edittool.php">  <h2>Tool Information (edit):</h2>  <table border="0">	<xsl:for-each select="tool/field">	<tr>	  <td><xsl:value-of select="@id"/></td>	  <td>	  <input type="text">	  <xsl:attribute name="id">		<xsl:value-of select="@id" />	  </xsl:attribute>	  <xsl:attribute name="name">		<xsl:value-of select="@id" />	  </xsl:attribute>	  <xsl:attribute name="value">		<xsl:value-of select="value" />	  </xsl:attribute>	  </input>	  </td>	</tr>	</xsl:for-each>  </table>  <br />  <input type="submit" id="btn_sub" name="btn_sub" value="Submit" />  <input type="reset" id="btn_res" name="btn_res" value="Reset" />  </form>  </body>  </html></xsl:template></xsl:stylesheet>

tool_updated.xsl

<?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/">  <html>  <body>  <h2>Updated Tool Information:</h2>  <table border="1">	<xsl:for-each select="tool/field">	<tr>	  <td><xsl:value-of select="@id" /></td>	  <td><xsl:value-of select="value" /></td>	</tr>	</xsl:for-each>  </table>  </body>  </html></xsl:template></xsl:stylesheet>

edittool.asp

<%function loadFile(xmlfile,xslfile)Dim xmlDoc,xslDoc'Load XML fileset xmlDoc = Server.CreateObject("Microsoft.XMLDOM")xmlDoc.async = falsexmlDoc.load(xmlfile)'Load XSL fileset xslDoc = Server.CreateObject("Microsoft.XMLDOM")xslDoc.async = falsexslDoc.load(xslfile)'Transform fileResponse.Write(xmlDoc.transformNode(xslDoc))end functionfunction updateFile(xmlfile)Dim xmlDoc,rootEl,fDim i'Load XML fileset xmlDoc = Server.CreateObject("Microsoft.XMLDOM")xmlDoc.async = falsexmlDoc.load(xmlfile)'Set the rootEl variable equal to the root elementSet rootEl = xmlDoc.documentElement'Loop through the form collectionfor i = 1 To Request.Form.Count  'Eliminate button elements in the form  if instr(1,Request.Form.Key(i),"btn_")=0 then	'The selectSingleNode method queries the XML file for a single node	'that matches a query. This query requests the value element that is	'the child of a field element that has an id attribute which matches	'the current key value in the Form Collection. When there is a match -	'set the text property equal to the value of the current field in the	'Form Collection.	set f = rootEl.selectSingleNode("field[@id='" & _	Request.Form.Key(i) & "']/value")	f.Text = Request.Form(i)  end ifnext'Save the modified XML filexmlDoc.save xmlfile'Release all object referencesset xmlDoc=nothingset rootEl=nothingset f=nothing'Load the modified XML file with a style sheet that'allows the client to see the edited informationloadFile xmlfile,server.MapPath("tool_updated.xsl")end function'If the form has been submitted update the'XML file and display result - if not,'transform the XML file for editingif Request.Form("btn_sub")="" then  loadFile server.MapPath("tool.xml"),server.MapPath("tool.xsl")else  updateFile server.MapPath("tool.xml")end if%>

Since i have php installed, i created a PHP alternative called edittool.php

<?phpfunction loadFile($xmlfile,$xslfile){  extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc=new DOMDocument();  $xmlDoc->async=false;  $xmlDoc->load($xmlfile);//Load XSL file  // $xslDoc is of type "Microsoft.XMLDOM"  $xslDoc=new DOMDocument();  $xslDoc->async=false;  $xslDoc->load($xslfile);  //Transform file  $xslt=new XSLTProcessor();  $xslt->importStylesheet($xslDoc);  print $xslt->transformToXML($xmlDoc);  return $function_ret;}function updateFile($xmlfile){  extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc=new DOMDocument();  $xmlDoc->async=false;  $xmlDoc->load($xmlfile);//Set the rootEl variable equal to the root element  $rootEl=$xmlDoc->documentElement;//Loop through the form collection  for ($i=1; $i<=count($_POST); $i=$i+1)  {//Eliminate button elements in the form	if ((strpos(($i),"btn_",1) ? strpos(($i),"btn_",1)+1 : 0))	{//The selectSingleNode method queries the XML file for a single node//that matches a query. This query requests the value element that is//the child of a field element that has an id attribute which matches//the current key value in the Form Collection. When there is a match -//set the text property equal to the value of the current field in the//Form Collection.	  $f=$rootEl->selectSingleNode("field[@id='".$i."']/value");	  $f->Text=$_POST[$i];	}   }//Save the modified XML file  $xmlDoc->save($xmlfile);//Release all object references  $xmlDoc=null;  $rootEl=null;  $f=null;//Load the modified XML file with a style sheet that//allows the client to see the edited information  loadFile($xmlfile,$DOCUMENT_ROOT."tool_updated.xsl");  return $function_ret;} //If the form has been submitted update the//XML file and display result - if not,//transform the XML file for editingif ($_POST["btn_sub"]==""){  loadFile($DOCUMENT_ROOT."tool.xml",$DOCUMENT_ROOT."tool.xsl");}  else{  updateFile($DOCUMENT_ROOT."tool.xml");} ?>

Now everything seems to work, except that the tool.xml file does not get updated with the changes made. Please advice.Regards.Eijaz

Link to post
Share on other sites

In PHP, variables are local by default. You have several functions, so the $xmlDoc and $xslDoc variables of one function are not available to the rest by default.The dirtiest and quickest solution is to simply declare $xmlDoc and $xslDoc outside of any funciton, ideally at the top, like:

<?php$xmlDoc;$xslDoc;//The rest of your existing code

Also, AFAIK, there isn't an "async" property to DOMDocument in PHP, so

  $xslDoc->async=false;

should go.

Link to post
Share on other sites

Nope. I tried that and it does not work!

<?php$xmlDoc=new DOMDocument();$xslDoc=new DOMDocument();function loadFile($xmlfile,$xslfile){extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc->load($xmlfile);//Load XSL file  // $xslDoc is of type "Microsoft.XMLDOM"  $xslDoc->load($xslfile);  //Transform file  $xslt=new XSLTProcessor();  $xslt->importStylesheet($xslDoc);  print $xslt->transformToXML($xmlDoc);//  return $function_ret;}function updateFile($xmlfile){extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc->load($xmlfile);  //Set the rootEl variable equal to the root element  $rootEl=$xmlDoc->documentElement;  //Loop through the form collection  $array_keys = array_keys($_POST);  for ($i=0; $i<count($array_keys)-1; $i++)  {//	echo $array_keys[$i] . " - " . $i;//Eliminate button elements in the form//	if ($array_keys[$i]!=="btn_sub")//	{//The selectSingleNode method queries the XML file for a single node//that matches a query. This query requests the value element that is//the child of a field element that has an id attribute which matches//the current key value in the Form Collection. When there is a match -//set the text property equal to the value of the current field in the//Form Collection.//		exit;[b]	   $f=$rootEl->GetElementsByTagName("field[@id='".$array_keys[$i]."']/value");	   $f->nodeValue=$_POST[$array_keys[$i]];[/b]//	}  }//Save the modified XML file  $xmlDoc->save($xmlfile);//Release all object references  $xmlDoc=null;  $rootEl=null;  $f=null;//Load the modified XML file with a style sheet that//allows the client to see the edited information  loadFile($xmlfile,$DOCUMENT_ROOT."tool_updated.xsl");//  return $function_ret;}//If the form has been submitted update the//XML file and display result - if not,//transform the XML file for editingif ($_POST["btn_sub"]==""){  echo "Its Load Time!"; loadFile($DOCUMENT_ROOT."tool.xml", $DOCUMENT_ROOT."tool.xsl");}  else{  echo "Its Update Time!";  updateFile($DOCUMENT_ROOT."tool.xml");}?>

i have looped through forms collections like this:

  //Loop through the form collection  $array_keys = array_keys($_POST);  for ($i=0; $i<count($array_keys)-1; $i++)  {

As you can see, i have edited the php code again and changed "SelectSingleNode" to GetElementsByTagName() as the former is a javascript function and not available in PHP. As i dont know its equivalent in PHP, i am trying "GetElementsByTagName()" & "NodeValue"..........but both dont seem to work, though i did not get any PHP errors...

$f=$rootEl->GetElementsByTagName("field[@id='".$array_keys[$i]."']/value");	   $f->nodeValue=$_POST[$array_keys[$i]];

Any ideas why the tool.xml file does not get updated??? And since there is an ASP code posted on the website, i would like to request the W3School.com site owners to post an equivalent PHP code for this tutorial.Right now, i am really stumped!!! IS THERE ANYONE WHO CAN HELP ME WITH THIS PHP CODE??? :)

Edited by sifar786
Link to post
Share on other sites

Well, done it myself after some trial and error with XPATH problem :)And here's the tested code for people out there!

<?php$xmlDoc=new DOMDocument();$xslDoc=new DOMDocument();$xmlDoc->preserveWhiteSpace = false;$xslDoc->preserveWhiteSpace = false;$xmlDoc->formatOutput = true;$xslDoc->formatOutput = true;function loadFile($xmlfile,$xslfile){extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc->load($xmlfile);//Load XSL file  // $xslDoc is of type "Microsoft.XMLDOM"  $xslDoc->load($xslfile);  //Transform file  $xslt=new XSLTProcessor();  $xslt->importStylesheet($xslDoc);  print $xslt->transformToXML($xmlDoc);}function updateFile($xmlfile){extract($GLOBALS);//Load XML file  // $xmlDoc is of type "Microsoft.XMLDOM"  $xmlDoc->load($xmlfile);  $xpath = new DOMXPath($xmlDoc);  //Set the rootEl variable equal to the root element  $rootEl=$xmlDoc->documentElement;  //Loop through the form collection  $array_keys = array_keys($_POST);  for ($i=0; $i<count($array_keys)-1; $i++)  {		$z=$array_keys[$i];		$nodeList=$xpath->query('/tool//field[@id="'.$z.'"]/value');		foreach ($nodeList as $n)		{			$n->nodeValue=$_POST[$array_keys[$i]];		}  }//Save the modified XML file  $xmlDoc->save($xmlfile);//Release all object references  $xmlDoc=null;  $rootEl=null;  $f=null;//Load the modified XML file with a style sheet that//allows the client to see the edited information  loadFile($xmlfile,$DOCUMENT_ROOT."tool_updated.xsl");}//If the form has been submitted update the//XML file and display result - if not, transform the XML file for editingif ($_POST["btn_sub"]==""){  echo "Its Load Time!"; loadFile($DOCUMENT_ROOT."tool.xml", $DOCUMENT_ROOT."tool.xsl");}  else{  echo "Its Update Time!";  updateFile($DOCUMENT_ROOT."tool.xml");}?>

Hope this helps!Cheers! :)

Link to post
Share on other sites
And since there is an ASP code posted on the website, i would like to request the W3School.com site owners to post an equivalent PHP code for this tutorial.
I'd like that too... and quite a few members have requested the same since the beginning of this forum. The authors at W3Schools appear not to be doing it for some reason... lack of time for it I guess.BTW, this part
//Release all object references  $xmlDoc=null;  $rootEl=null;  $f=null;

is totally needless in PHP.

Link to post
Share on other sites
Thanks....i missed removing that part... :)BTW, just a question:
why is it that > OR > works both in IE & FF and < OR < does not in IE & FF???

Where is that? In XSLT? It should work everywhere. A code sample would be good to see what you're talking about.
Link to post
Share on other sites

Here's the link:IF exampleThe XML file:--------------

<?xml version="1.0" encoding="ISO-8859-1"?><!-- Edited by XMLSpy® --><catalog>	<cd>		<title>Empire Burlesque</title>		<artist>Bob Dylan</artist>		<country>USA</country>		<company>Columbia</company>		<price>10.90</price>		<year>1985</year>	</cd>	<cd>		<title>Hide your heart</title>		<artist>Bonnie Tyler</artist>		<country>UK</country>		<company>CBS Records</company>		<price>9.90</price>		<year>1988</year>	</cd>	<cd>		<title>Greatest Hits</title>		<artist>Dolly Parton</artist>		<country>USA</country>		<company>RCA</company>		<price>9.90</price>		<year>1982</year>	</cd>	<cd>		<title>Still got the blues</title>		<artist>Gary Moore</artist>		<country>UK</country>		<company>Virgin records</company>		<price>10.20</price>		<year>1990</year>	</cd>	<cd>		<title>Eros</title>		<artist>Eros Ramazzotti</artist>		<country>EU</country>		<company>BMG</company>		<price>9.90</price>		<year>1997</year>	</cd>	<cd>		<title>One night only</title>		<artist>Bee Gees</artist>		<country>UK</country>		<company>Polydor</company>		<price>10.90</price>		<year>1998</year>	</cd>	<cd>		<title>Sylvias Mother</title>		<artist>Dr.Hook</artist>		<country>UK</country>		<company>CBS</company>		<price>8.10</price>		<year>1973</year>	</cd>	<cd>		<title>Maggie May</title>		<artist>Rod Stewart</artist>		<country>UK</country>		<company>Pickwick</company>		<price>8.50</price>		<year>1990</year>	</cd>	<cd>		<title>Romanza</title>		<artist>Andrea Bocelli</artist>		<country>EU</country>		<company>Polydor</company>		<price>10.80</price>		<year>1996</year>	</cd>	<cd>		<title>When a man loves a woman</title>		<artist>Percy Sledge</artist>		<country>USA</country>		<company>Atlantic</company>		<price>8.70</price>		<year>1987</year>	</cd>	<cd>		<title>Black angel</title>		<artist>Savage Rose</artist>		<country>EU</country>		<company>Mega</company>		<price>10.90</price>		<year>1995</year>	</cd>	<cd>		<title>1999 Grammy Nominees</title>		<artist>Many</artist>		<country>USA</country>		<company>Grammy</company>		<price>10.20</price>		<year>1999</year>	</cd>	<cd>		<title>For the good times</title>		<artist>Kenny Rogers</artist>		<country>UK</country>		<company>Mucik Master</company>		<price>8.70</price>		<year>1995</year>	</cd>	<cd>		<title>Big Willie style</title>		<artist>Will Smith</artist>		<country>USA</country>		<company>Columbia</company>		<price>9.90</price>		<year>1997</year>	</cd>	<cd>		<title>Tupelo Honey</title>		<artist>Van Morrison</artist>		<country>UK</country>		<company>Polydor</company>		<price>8.20</price>		<year>1971</year>	</cd>	<cd>		<title>Soulsville</title>		<artist>Jorn Hoel</artist>		<country>Norway</country>		<company>WEA</company>		<price>7.90</price>		<year>1996</year>	</cd>	<cd>		<title>The very best of</title>		<artist>Cat Stevens</artist>		<country>UK</country>		<company>Island</company>		<price>8.90</price>		<year>1990</year>	</cd>	<cd>		<title>Stop</title>		<artist>Sam Brown</artist>		<country>UK</country>		<company>A and M</company>		<price>8.90</price>		<year>1988</year>	</cd>	<cd>		<title>Bridge of Spies</title>		<artist>T`Pau</artist>		<country>UK</country>		<company>Siren</company>		<price>7.90</price>		<year>1987</year>	</cd>	<cd>		<title>Private Dancer</title>		<artist>Tina Turner</artist>		<country>UK</country>		<company>Capitol</company>		<price>8.90</price>		<year>1983</year>	</cd>	<cd>		<title>Midt om natten</title>		<artist>Kim Larsen</artist>		<country>EU</country>		<company>Medley</company>		<price>7.80</price>		<year>1983</year>	</cd>	<cd>		<title>Pavarotti Gala Concert</title>		<artist>Luciano Pavarotti</artist>		<country>UK</country>		<company>DECCA</company>		<price>9.90</price>		<year>1991</year>	</cd>	<cd>		<title>The dock of the bay</title>		<artist>Otis Redding</artist>		<country>USA</country>		<company>Atlantic</company>		<price>7.90</price>		<year>1987</year>	</cd>	<cd>		<title>Picture book</title>		<artist>Simply Red</artist>		<country>EU</country>		<company>Elektra</company>		<price>7.20</price>		<year>1985</year>	</cd>	<cd>		<title>Red</title>		<artist>The Communards</artist>		<country>UK</country>		<company>London</company>		<price>7.80</price>		<year>1987</year>	</cd>	<cd>		<title>Unchain my heart</title>		<artist>Joe Cocker</artist>		<country>USA</country>		<company>EMI</company>		<price>8.20</price>		<year>1987</year>	</cd></catalog>

The XSL file:--------------

<?xml version="1.0" encoding="ISO-8859-1"?><!-- Edited by XMLSpy® --><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/">  <html>  <body>	<h2>My CD Collection</h2>	<table border="1">	  <tr bgcolor="#9acd32">	  <th>Title</th>	  <th>Artist</th>	</tr>	<xsl:for-each select="catalog/cd">	<xsl:if test="price < 10">	  <tr>		<td><xsl:value-of select="title"/></td>		<td><xsl:value-of select="artist"/></td>		</tr>	</xsl:if>	</xsl:for-each>	</table>  </body>  </html></xsl:template></xsl:stylesheet>

Here i have changed the > (>) to < (<).......doesnt seem to work on both browsers and gives error even if i use the escape sequence for '<' ....

Link to post
Share on other sites
<?xml version="1.0" encoding="ISO-8859-1"?><!-- Edited by XMLSpy® --><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/">  <html>  <body>	<h2>My CD Collection</h2>	<table border="1">	  <tr bgcolor="#9acd32">	  <th>Title</th>	  <th>Artist</th>	</tr>	<xsl:for-each select="catalog/cd">	<xsl:if test="price > 10">	  <tr>		<td><xsl:value-of select="title"/></td>		<td><xsl:value-of select="artist"/></td>		</tr>	</xsl:if>	</xsl:for-each>	</table>  </body>  </html></xsl:template></xsl:stylesheet>

Should work. Are you sure this is the ONLY thing you've altered? Any error messages coming from the browser?

Link to post
Share on other sites

Can you give a link to your copy? And again, any error messages? I know for sure that IE should show you a meaningful one (not as sure about Firefox...).

Link to post
Share on other sites

No, i am just learning XML, XSLT thru the websites W3SCHOOLS & TIZAG.so i am just changing it on this online translator or copying it to a file and testing it on my localhost having XAMPP.Firefox 3.5.7 error:

Error in XSLTXML Parsing Error: not well-formed Location: http://www.w3schools.com/xsl/tryxslt_result.asp Line Number 15, Column 25:

Internet Explorer 8 error:

Error in XSLTLine 15: The character '<' cannot be used in an attribute value.

Now, the funny part is that this works both in IE & FF,

<xsl:if test="price > 10">

But this doesn't!

<xsl:if test="price < 10">

Though i must say, its been fun with XML, XSL and looking forward to use it to enhance my career :)

Edited by sifar786
Link to post
Share on other sites

This is a bug in W3Schools' Tryit Editor, I think. It reencodes your XSLT, thus turning

<

into

<

At which point, the line

<xsl:if test="price < 10">

Indeed becomes a non well formed XML.If you save both files locally, and add the xml-stylesheet PI to the XML, it will work at your XAMPP setup.

Link to post
Share on other sites

The XML defines "<" as the start of a tag. It also defines ">" as the end of a tag. However, to let people make up some space (">" is four bytes, while ">" is just one), ">" is allowed within text nodes. "<" is not allowed, because it has the special meaning of starting a tag. Allowing ">" is acceptable, because if you haven't started a tag, you can safely assume it's not ending at the point of ">".

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...