List xml nodes and attribute name from xml - javascript

How to retreive node_names and attribute_names from a xml (not values of node or attributes) Is it possible using jquery?
<Client>
<product name="astro">
<service_process name="ACID">
<host>pable</host>
<port>18848</port>
</servcice_process>
<service_process name="Mestro">
<host>Mico</host>
<port>18821</port>
</servcice_process>
</product>
</Client>

You could start with something like this:
var xml = '<Client><product name="astro"><service_process name="ACID"><host>pable</host><port>18848</port></servcice_process><service_process name="Mestro"><host>Mico</host><port>18821</port></servcice_process></product></Client>';
$(xml).each(function displayChildren (i, node) {
console.log(node.nodeName);
// traverse attributes
$.each(node.attributes, function (j, attr) {
console.log(attr.nodeName, attr.nodeValue);
});
// recursive call
$(node).children().each(displayChildren);
});

A quick search revealed this page which deals in XML Parsing with jQuery. Getting the node name is a little more difficult but a method for getting it is provided here. From a quick look, I'm assuming you'd want to do something along the lines of:
$(xml).each(function(){ //xml is the XML resource.
if($(this).attr("name")!=""){
alert("Name = " + $(this).attr("name"));
}
alert("Node = " + $(this).get(0).TagName);
});
I believe this should work no problems.

Related

Splitting a JavaScript string from XML and wrapping in HTML element

I'm working on displaying an RSS feed in a website through the use of jQuery and AJAX. One of the strings from the source XML file are wrapped in a <category> tag, and there are multiple of these returned. I'm getting the source data like follows:
var _category = $(this).find('category').text();
Because there are multiple categories returned with this method, say the following:
<category>Travel</category>
<category>Business</category>
<category>Lifestyle</category>
I'm getting strings returned like so:
TravelBusinessLifestyle
My end goal is to see each of these separate strings returned and wrapped in individual HTML elements, such as <div class="new"></div>.
I did end up trying the following:
var _categoryContainer = $(this)
.find('category')
.each(function () {
$(this).wrap( "<div class='new'></div>" );
});
among quite a few other variations.
This is all being appended to a HTML structure similar to the following.
// Add XML content to the HTML structure
$(".rss .rss-loader")
.append(
'<div class="col">'
+ <h5 class="myClass">myTitle</h5>
+ _category
+ "</div>"
);
Any suggestions would be much appreciated!
if it's a simple html which is mentioned in a question. you can use something like below.
var html="<category>Travel</category><category>Business</category><category>Lifestyle</category>"
var htmlObj=$.parseHTML(html);
var container=$("#container")
$.each(htmlObj,function(i,o){
container.append("<div class='new'>"+o.innerText+"</div>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>
Same as first answer, but without jquery
let container = document.querySelector('div#container');
document.querySelectorAll('category').forEach(element => {
let div = document.createElement('div');
div.innerText = element.innerText;
container.appendChild(div);
})
<category>Travel</category><category>Business</category><category>Lifestyle</category>
<div id="container"></div>

Render JSON into HTML

I get JSON data with next code:
$.getJSON(
"data.json",function foo(result) {
$.each(result[1].data.children.slice(0, 10),
function (i, post) {
$("#content").append( '<br> HTML <br>' + post.data.body_html );
}
)
}
)
<div id="content"></div>
Some of strings included : < and > and this did not displaying as regular html <, >
Try to use .html() instead .append() did not work.
Here is live example http://jsfiddle.net/u6yUN/
Just use the 3rd (space) parameter of JSON.stringify to format the json, and use <pre> tags to display.
const json = { foo: { bar: 'hello' } }
$('html').append('<pre>' + JSON.stringify(json, null, 2) + '</pre>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you're looking for a nice collapsible render I've written a module to this. It's in pure JavaScript so you can use it in any framework.
mohsen1/json-formatter-js
It's also available as an AngularJS directive if you are using AngularJS
mohsen1/json-formatter
Checkout the demo here: AngularJS directive demo
It's also theme-able, so you can change the colors:
Here is whet you were asking for: Complete JSFiddle Demo
var jsonRequestUrl = 'http://www.reddit.com/r/funny/comments/1v6rrq.json';
var decoder = $('<div />');
var decodedText = '';
$.getJSON(jsonRequestUrl, function foo(result) {
var elements = result[1].data.children.slice(0, 10);
$.each(elements, function (index, value) {
decoder.html(value.data.body_html);
decodedText += decoder.text();
});
$('#content').append(decodedText);
});
Edit: Keeping this here as a simpler example.
// Encoded html
var encoded = '<div style="background:#FF0">Hello World</div>';
// Temp div to render html internally
var decode = $('<div />').html(encoded).text();
// Add rendered html to DOM
$('#output').append(decode);
DEMO
Another library that works for rendering JSON objects is: renderjson
Although it has a minimalistic style, it allows to click through the JSON structure.
Example usage:
document.getElementById("test").appendChild (renderjson (data));
You may want to give JSON2HTML a try. Works with native JavaScript, with jQuery and with node.js. Allows to completely customize the generated HTML.
Use $.parseHTML() jQuery method
var myData = "yourHtml with <" //
$("#content").append($.parseHTML(myData));
Here it is a jsfiddle: http://jsfiddle.net/x4haw/
One of the easiest way is
var t= post.data.body_html;
t.replace('&lt','<').replace('&gt', '>');
$("#content").append( '<br> HTML <br>' + t );
try this way...
var htmlString = $("<div/>").html(data).text();

parsing some XML with JS:

I have a XML file that is used by Flash as string resource
I would like my JS to use that XML as well: is there an easy way to read and parse external XML file in JS ?
like resources.xml that contains:
<resources locale="en">
<sizeUp>Size up</sizeUp>
<sizeDown>Size Down</sizeDown>
<clearSearch>Clear search</clearSearch>
<wouldYouLikeToReport>Would you like to report this user for abuse ?</wouldYouLikeToReport>
<yes>Yes</yes>
....
If you want to get every node and the text it contains, try this:
var xml;
xml = '<resources locale="en">';
xml += '<sizeUp>Size up</sizeUp>';
xml += '<sizeDown>Size Down</sizeDown>';
$(xml).children().each(function(index, elem) {
var $element = $(elem);
var text = $element.text();
console.log('elem is ');
console.log(elem);
console.log('text is ');
console.log(text);
});
The output will be:
elem is
sizeup
text is
Size up
elem is
sizedown
text is
Size Down
If you are looking for the contents of a specific tag, you could do:
console.log('sizeUp is ');
console.log($(xml).find('sizeUp').text());

Get JSON data from external URL and insert in a div as plain text

I have written a function to display some paragraph tags from an external webpage. For some reason the results are displayed in firebug console but not showing on the web page as I wanted (blank page).
function requestCrossDomain(callback){
var querylink = "select * from html where url='http://somedomain.com'" +
" and xpath='/html/body/div/div/div[2]/div/div/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
if (typeof callback === 'function'){
callback(data);
}
});
}
My firebug console shows the below value.
{"query":{"count":1,"created":"2013-12-23T06:31:46Z","lang":"en-US","results":{"dd":{"p":"Hills: High"}}}}
How can I modify the code to display the value of the P tag, which is "Hills: High"
I'm calling the function from HTML code and trying to display the value inside "#targetWrapper"
requestCrossDomain(function(results){
$('#targetWrapper').html(results);
});
Edited to reflect a functional fiddle
$(document).ready(function(){
requestCrossDomain();
});
function requestCrossDomain(){
var querylink = "select * from html where url='http://www.bom.gov.au/wa/forecasts" +
"/armadale.shtml' and xpath='/html/body/div/div/div[2]/div/div" +
"/div/dl'";
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent(querylink) + '&format=json&callback?';
$.getJSON(yql, function(data){
$('#targetWrapper').html(data.query.results.dl.dd[0].p);
$("#targetWrapper").append("<br/><strong>" + JSON.stringify(data) + "</strong>");
});
}
Your data format was very much off the mark AND you cannot have two functions with the same name.
The object you get back from $.getJSON is a simple Javascript Object. You can access it just as you would any other object:
In this case, you'd use:
requestCrossDomain(function(results) {
$("#targetWrapper").html(results.query.results.dd.p);
}
I would highly recommend that you read the MDN documentation I linked above. Having MDN bookmarked is also a good idea; it's a great resource to have easy access to.

Parse JavaScript with jsoup

In an HTML page, I want to pick the value of a javascript variable.
Below is the snippet of HTML page:
<input id="hidval" value="" type="hidden">
<form method="post" style="padding: 0px;margin: 0px;" name="profile" autocomplete="off">
<input name="pqRjnA" id="pqRjnA" value="" type="hidden">
<script type="text/javascript">
key="pqRjnA";
</script>
My aim is to read the value of variable key from this page using jsoup.
Is it possible with jsoup? If yes then how?
Since jsoup isn't a javascript library you have two ways to solve this:
A. Use a javascript library
Pro:
Full Javascript support
Con:
Additional libraray / dependencies
B. Use Jsoup + manual parsing
Pro:
No extra libraries required
Enough for simple tasks
Con:
Not as flexible as a javascript library
Here's an example how to get the key with jsoupand some "manual" code:
Document doc = ...
Element script = doc.select("script").first(); // Get the script part
Pattern p = Pattern.compile("(?is)key=\"(.+?)\""); // Regex for the value of the key
Matcher m = p.matcher(script.html()); // you have to use html here and NOT text! Text will drop the 'key' part
while( m.find() )
{
System.out.println(m.group()); // the whole key ('key = value')
System.out.println(m.group(1)); // value only
}
Output (using your html part):
key="pqRjnA"
pqRjnA
The Kotlin question is marked as duplicate and is directed to this question.
So, here is how I did that with Kotlin:
val (key, value) = document
.select("script")
.map(Element::data)
.first { "key" in it } // OR single { "key" in it }
.split("=")
.map(String::trim)
val pureValue = value.replace(Regex("""["';]"""), "")
println("$key::$pureValue") // key::pqRjnA
Another version:
val (key, value) = document
.select("script")
.first { Regex("""key\s*=\s*["'].*["'];""") in it.data() }
.data()
.split("=")
.map { it.replace(Regex("""[\s"';]"""), "") }
println("$key::$value") // key::pqRjnA
Footnote
To get the document you can do this:
From a file:
val input = File("my-document.html")
val document = Jsoup.parse(input, "UTF-8")
From a server:
val document = Jsoup.connect("the/target/url")
.userAgent("Mozilla")
.get()

Categories