0

I got a xml data as string variable. it has many sets of <item>...</item> I wonder how I can extract all data of <name>..</name> for all the <item> sets and output them in to textarea using javascript?

Note: getjson grabs the remote xml and puts it as content variable: xml set example:

<item>
<title>rober album</title>
<link></link>
<description></description>
<location></location>
<image_url></image_url>
<name>robert</name>
</item>

code:

    <script>
    $.getJSON('http://anyorigin.com/get?url=http://asite.com/feed/latest&callback=?', function(data){
    var Content = data.contents;  
//here i want to parse all name element of remote xml and put it in textarea  
     });
    </script>

</head>
<body>
<td><textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea></td>
2
  • It's pretty unclear. You say you have XML data, but in the second piece of code there's an ajax call which returns JSON data. Is it unrelated? Where's your XML stored? Commented May 11, 2013 at 12:08
  • thanks for reply .getjson gets the xml from remote server and now i want to parse all name elements from that remote xml .Getjson holds the whole remote xml as string content. Commented May 11, 2013 at 12:13

1 Answer 1

1

I've put together a small script which will pretty much explain itself. It will loop trough all the ITEM nodes in the XML document loaded from a string (getJSON in your case), and alerts all the names. You should be able to take it from here ;)

var xmlData = "<items><item><title>rober album</title><link></link><description></description><location></location><image_url></image_url><name>robert</name></item><item><title>robert 2</title><link></link><description>/description><location></location><image_url></image_url><name>Jack</name></item></items>";

var parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlData,"text/xml");

var items = xmlDoc.getElementsByTagName("item");

for(i = 0; i < items.length; i++)
    alert(items[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);

For more details on working with XML in javascript, check out the documentation at w3s: http://www.w3schools.com/xml/xml_dom.asp

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks it worked .So i can retrieve multiple diffrent elements inside for loop too(for example image_url)?
yeah, you can access any child node you want with the getElementsByTageName() function, which returns an array with all the matching nodes. Play around with it a bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.