jquery to retrieve a top level xml node - javascript

I have tried to retrieve the top level 'label' attribute from the following xml using jquery, and having parsed it into a DOM object with no luck. Any suggestions on how I can do this ? I've tried using children(),parent() functions with no luck - I get either no result, or end up having all instances of the label tags passed back to me.
jquery:
xml = $.parseXML(xmlString);
$xml = $(xml);
I traverse fields via $($xml).find('fields').each(function(){ etc...
but cannot get that top level label data!
<customobject>
<label>want this content</label>
<fields>
<label>foo</label>
<attr1></attr1>
<attr2></attr2>
</fields>
<fields>
<label>foo2</label>
<attr1></attr1>
<attr2></attr2>
</fields>
</customobject>

You can look for label which is a child of customobject like below. Just using find('label') will return contents from all the label elements
var xmlString = '<customobject><label>want this content</label><fields><label>foo</label><attr1></attr1><attr2></attr2></fields><fields><label>foo2</label><attr1></attr1><attr2></attr2></fields></customobject>';
var xml = $.parseXML(xmlString);
var $xml = $(xml);
alert($xml.find('customobject > label').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hope this will be helpful
var xml = "<customobject>"+
"<label>want this content</label>"+
"<fields>"+
"<label>foo</label>"+
"<attr1></attr1>"+
"<attr2></attr2>"+
"</fields>"+
"<fields>"+
"<label>foo2</label>"+
"<attr1></attr1>"+
"<attr2></attr2>"+
"</fields>"+
"</customobject>";
xmlDoc = $.parseXML(xml ),
$xml = $( xmlDoc ),
$firstLabelbject = $xml.find( "customobject label")[0].innerHTML; // Will select first label
console.log($firstLabelbject);
JSFIDDLE EXAMPLE

Related

How to append a div with a new div and put var inside that new div

I am getting data from a XML and displaying it, but if I append another div with a var inside a new div, I get [object Object] instead of the XML data. How can I append a div with a new div plus var inside, this is what im trying to do
$('#channels').append('<div id="logo">'+$(this).find("display-name")+'</div>');
below is the full code im using
<div class="channels" id="channels"></div>
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$xml.find('channel').each(function (i,e) {
$('#channels').append('<div id="logo">'+$(this).find("display-name")+'</div>');
});
$(...).find() yields a jQuery object which serializes to [object Object]. You wanted to get the text instead; use text() method on the objects for that:
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$xml.find('channel').each(function(i, e) {
$('#channels').append('<div id="logo">' + $(this).find("display-name").text() + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="channels" id="channels"></div>

How do I append these two XMLs together?

I'm trying to append xmlTwo inside the xmlOne yellow node, but I'm getting an error. What am I doing wrong?
var xmlOne =
$.parseXML(
"<xml xmlns=\"mynamespace\">\
<red>\
<orange>\
<yellow>\
</yellow>\
</orange>\
</red>\
</xml>"
);
var xmlTwo =
$.parseXML(
"<green>\
<blue>I'm in blue!</blue>\
</green>"
);
var xmlThree = xmlOne.getElementsByTagName("yellow")[0].appendChild(xmlTwo);
console.log(xmlThree);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Parse the first element, the root one.
Keep the second XML element as string.
Find the node in the first element where you want to append the other XML.
Append the XML into the node.
var xmlOne =
$.parseXML(
"<xml xmlns=\"mynamespace\">\
<red>\
<orange>\
<yellow>\
</yellow>\
</orange>\
</red>\
</xml>"
);
var xmlTwoNotParsed =
"<green>\
<blue>I'm in blue!</blue>\
</green>";
var yellowNode = $(xmlOne).find("yellow");
yellowNode.append(xmlTwoNotParsed);
console.log(xmlOne);

innerHTML missing when XML parsing with jQuery in IE9 but not Chrome

I'm using jQuery's XML parser on some simple content that contains HTML.
Extracting the full HTML text using jQuery's .html() or standard javascript .innerHTML works fine in Chrome, but not in Internet Explorer 9. jQuery's .text() works in both cases, but I need the html tags extracted as well.
How can I make it work with IE9 as well?
You can test it out here:
http://jsfiddle.net/199vLsgz/
XML:
<script id="xml_data" type="text/xml">
<model_data name="The model ">
<person_responsible></person_responsible>
<objects>
<object name="Available B reports" id="obj1" >
<description>this is a description <br/> oh look, another line!</description>
</object>
</objects>
</model_data>
</script>
Code:
$(function() {
var xml = $("#xml_data").text();
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
alert(desc.html());
})
Xml elements do not have innerHTML defined inside IE which is what's being used with the html function of jquery.
Firstly you need to use CDATA to preserve tags inside xml tags
<description><![CDATA[this is a description <br/> oh look, another line!]]></description>
then you can try to use the textContent property:
alert(desc[0].textContent); //desc.text() will also work now
And you also can add the content correctly using something like:
$('#some-container').html(desc[0].textContent);
$(function() {
var xml = $("#xml_data").text();
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
console.log($xml)
var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
alert(desc[0].textContent);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script id="xml_data" type="text/xml">
<model_data name="The model">
<person_responsible></person_responsible>
<objects>
<object name="Available B reports" id="obj1" >
<description><![CDATA[this is a description <br/> oh look, another line!]]></description>
</object>
</objects>
</model_data>
</script>

cannot get xmlDoc to load any value. Keep getting null values

I have an xml file that I retreive via terminal emulation. I want to parse the results into a textarea in html. I am able to view the file in the textarea in xml format but have been unable to parse it into lines of the inner text.
Here is the javascript/jquery:
var x = ""
var y = ""
var Command="";
var cmd=""
$(document).ready(function() {
alert('jquery working');
$('#tester').click(function() {
$("#disptext").val("");
var APOresp = new ActiveXObject("DAT32COM.TERMINALEMULATION");
var Command = "<FORMAT>>*IA</FORMAT>";
APOresp.MakeEntry(Command);
//APOresp.GetMore(true,false);
var x = APOresp.ResponseXML;
APOresp.Close();
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(x);
$(x).find('RESPONSE').each(function() { //these lines do not work. I get null xmlDoc reference
$("#disptext").val($(this).text() + "<br />");
});
//$("#disptext").val(xmlDoc.xml); //disptext is the textarea
});
Here is what a portion of the text file looks like:
?xml version="1.0"?>
<!--This is a host terminal response-->
<RESPONSE xmlns="x-schema:C:\fp\swdir\Content\emulation-schema.xml">
<LINE INDEX="1"><![CDATA[SIGN IN ]]><CARRIAGE_RETURN/></LINE>
<LINE INDEX="2"><SOM/></LINE>
</RESPONSE>
Most files are much longer.
I want to get the text for each "LINE: tag and loop it into the textarea. It does put in the whole xml file in xml format if I use the last commented out line in the javascript file. For some unknown reason, I am unable to use the xmlDoc. I keep getting errors that the xmlDoc has null values. I have been trying to fix this for a number of days without success. Any help would be greatly appreciated.

Image Slider for Normal Data to xml data

I am using a normal variable to display the list of images. But the same thing I need is by using the XML. Can anyone please help me. The var 'imgs' should be an xml.
Jquery
$(function() {
var imgs = ['http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg', 'http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg', 'http://www.behok.ru/i/a/cat/gerbera.jpg', 'http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg', 'http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg'];
var maximages = imgs.length; //No of Images
Slider();
setInterval(Slider, 3000);
var prevIndex = 0, prevPrevIndex = 0;
function Slider() {
$('#imageSlide').fadeOut("slow", function() {
do {
shuffleIndex = Math.floor(Math.random() * maximages);
} while(prevIndex == shuffleIndex || prevPrevIndex == shuffleIndex)
prevPrevIndex = prevIndex;
prevIndex = shuffleIndex;
$("#panel").fadeIn("slow").css('background', '#000');
$(this).attr('src', imgs[shuffleIndex]).fadeIn("slow");
});
}
});
I am assuming you want the image urls in xml format and then you want to parse this xml.
<images>
<image-url>http://www.academyflorists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg</image-url>
<image-url>http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg</image-url>
<image-url>http://www.behok.ru/i/a/cat/gerbera.jpg</image-url>
<image-url>http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg</image-url>
<image-url>http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg</image-url>
</images>
The you can parse it in the following way
var imgs = "<images><image-url>'http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg'</image-url><image-url>'http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg'</image-url><image-url>'http://www.behok.ru/i/a/cat/gerbera.jpg'</image-url><image-url>'http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg'</image-url><image-url>'http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg'</image-url></images>"
$xml = $.parseXML(imgs)
images = []
$($($xml).find('image-url')).each(function() { images.push($(this).text()) })
images will contain an array of all the image urls
You haven't told us what your xml would look like so I've together the following basic schema
<?xml version="1.0" encoding="utf-8" ?>
<images>
<image>url of image</image>
<image>url of next image</image>
<images>
If you search the jQuery site you will find that it tells you how to work with Xml - http://api.jquery.com/jQuery.parseXML/
You need to use parseXML on your xml string and convert to a jQuery object. You can then find() elements, loop through elements or pickout the elements text and attributes. The following example shows this.
$(function() {
// your image list as xml string
var xmlStr = '<?xml version="1.0" encoding="utf-8" ?><images><image>http://www.academy-florists.com/images/shop/thumbnails%5CValentines_Day_flowers.jpg</image><image>http://www.everythingbuttheprincess.com/assets/images/babies-in-bloom-fuchsia-flower_thumbnail.jpg</image><image>http://www.behok.ru/i/a/cat/gerbera.jpg</image><image>http://www.thebutterflygrove.com/images/thumbnails/0/200/200/thumbnail_flower-decor-makpk.jpg</image><image>http://gameinfestedent.com/gallery_photo/medium_image/image1322820610_MainPurpleOrchids3_1a.jpg</image></images>';
// parse the xml and produce an jQuery image object ($image) to represent the list of image elements
var xmlDoc = $.parseXML(xmlStr),
$xml = $(xmlDoc),
$image = $xml.find("image");
// loop throught your image elements and alert the url
$image.each(function() {
var imageElement = this, // this within the loop is the current element
$imageElement = $(imageElement),
imageUrl = $imageElement.text(); // use text to get the url
alert(imageUrl);
});
// use length on the jQuery object to get the element count
var maximages = $image.length;
alert(maximages);
var shuffleIndex = 3,
imageElement = $image[shuffleIndex], // index the random image that you want to use
$imageElement = $(imageElement),
imageUrl = $imageElement.text();
alert(imageUrl);
});

Categories