Friday, 8 July 2011

Read an XML inside Javascript - Object doesnt support this property or method ( ERROR )

Have you even faced with such an error. Ya many times even i have faced. Let me tell you when have i faced this kind of situation.

When i tried to use getElementsByTagName method for looping through an xml and get the node values. We get this error because the xml you are trying to is a string.

Here what we need to do is parse the xml using a dom parser and convert the xml from a string into an xml. Once this is done you could use getElementsByTagName method to loop through and get the value.

I know for everyone its hard to get clear with theoretical than a practical one.

Here i will give you an one:

var xml = "<persons><person><name>Jack</name><address>US</address><person><name>Rose</name><address>UK</address></person></persons>";

This is our xml. Now if we try
xml.getElementsByTagName("name");
then we will get an error.

Instead go for the following steps.
parser=new DOMParser();
xmlDoc=parser.parseFromString(xml,"text/xml");
Then you use
xml.getElementsByTagName("name");
You will be succeeded.

All the best to everyone for their work. Cheers !!

0 comments:

Post a Comment