I'm trying to grab an xml node by its attribute.
edit
I'm trying to retrieve an element by its attribute value using javascript xml instead of jquery. Is there a simple method for this?
It is really easy using jQuery. Suppose we have a string like this.
<document>
<value type="people">
<name>
John
</name>
</value>
<value type="vehicle">
<name>
Ford
</name>
</value>
</document>
Then
var xmlDocument = $.parseXML(str);
$(xmlDocument).find("value[type='people'] name").text()
We will get string 'John' back.
You have to find a list of elements first, then filter by their attributes.
Check out my demo here: http://jsfiddle.net/silkster/eDP5V/
I feel this justifies a new answer as it is JQuery Free
document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName((tagName || '*'));
return $A(children).inject([], function(elements, child) {
var attributeValue = child.getAttribute(attribute);
if(attributeValue != null) {
if(!value || attributeValue == value) {
elements.push(child);
}
}
return elements;
});
}
source
it has been pointed out to me that I posted the wrong script.. hehe read here
// document.getElementsByAttribute([string attributeName],[string attributeValue],[boolean isCommaHyphenOrSpaceSeparatedList:false])
document.getElementsByAttribute=function(attrN,attrV,multi){
attrV=attrV.replace(/\|/g,'\\|').replace(/\[/g,'\\[').replace(/\(/g,'\\(').replace(/\+/g,'\\+').replace(/\./g,'\\.').replace(/\*/g,'\\*').replace(/\?/g,'\\?').replace(/\//g,'\\/');
var
multi=typeof multi!='undefined'?
multi:
false,
cIterate=document.getElementsByTagName('*'),
aResponse=[],
attr,
re=new RegExp(multi?'\\b'+attrV+'\\b':'^'+attrV+'$'),
i=0,
elm;
while((elm=cIterate.item(i++))){
attr=elm.getAttributeNode(attrN);
if(attr &&
attr.specified &&
re.test(attr.value)
)
aResponse.push(elm);
}
return aResponse;
}
jquery can do this very easily. http://think2loud.com/224-reading-xml-with-jquery/
Related
I'm using JS to search in an XML and get it's elements in order to use it in further processing, I'm using heapbox to display the elements and then using .selected to get the selected element in order to display it's children.
The problem here is that i want to get the selected element in order to make some name processing before getting children, but i got nothing when storing it in a var and got it works when using the full query directly,
for ex,
var section = '', text = '' ;
section = $('menu').find($(".selected").text()).attr('nodeName');
alert($('menu').find($(".selected").text()).attr('nodeName'));
in that code section equals nothing, text equals nothing, it alerts undefined, while using $('menu').find($(".selected").text()).attr('nodeName') directly in processing works very good.
UPDATE:
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<menu parent_id="0" >
<Menu cat="main">
</Menu>
<Soup cat="main">
<Mushrom0Tomato.Soap price = "15.95" hasoption = "false">
</Mushrom0Tomato.Soap>
<Cream.Of.Chicken.Soap price = "16.95" hasoption = "true">
<Add.Mushroom price = "3.95"></Add.Mushroom>
<none price = "0"></none>
</Cream.Of.Chicken.Soap>
<Season.Soap price = "15.95" hasoption = "false">
</Season.Soap>
</Soup>
</menu>
JS code:
var cats=[], cati=0, total=0, selectedarray=[], itemoptions=[], optionstring='', section='', si=0, oi=0, items=[];
$("#total").append("Total: " + total + " EGP");
$('#dummy').load('cafe.xml',function() {
initialize();
})
function initialize(){
ct=$('menu').children().length;
for(cati==0;cati<=ct-1;cati++)
{
cats[cati]=$('menu').children().eq(cati).prop('nodeName');
var realname = cats[cati];
if(realname.indexOf(".") != -1){
realname = realname.replace(/\./g,' ');
}
$('.basic-example').append('<option value="option1">'+realname+'</option>');
}
$(".basic-example").heapbox({'onChange':function(){loadmenu()},effect:{type:"fade",speed:"slow"}});
}
// loading the items to the menu
function loadmenu()
{
$("#gallery").empty();
section = $('menu').find($(".selected").text()).attr('nodeName');
alert($("menu .selected").text().toString());
.
.
.
.find is meant for finding children elements of a selected node
You probably just want
$("menu .selected").text();
And
$("menu .selected").attr("nodeName");
The .find equivalent of this (although probably unnecessary) would be
$("menu").find(".selected").text();
And
$("menu").find(".selected").attr("nodeName");
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()
Hi I have this code that is all working in FF, except for the variable populated by a .text() method in IE.
The example code is below:
<script language="javascript" type="text/javascript">
$(document).find('f').each(function(){
var ff= $(this).attr("m");
var fmsg = $(this).text();
alert(ff + ' - ' +fmsg);
});
</script>
The data (document):
<data>
<f m="1">hi</f>
<f m="2">bye</f>
</data>
Why is the alert not showing '1 - hi' and '2 - bye', instead its showing an empty value for the fmsg variable. Any suggestions? Here is a working example: http://jsfiddle.net/dtuce/1/
The jQuery#text method doesn't really seem to be prepared to gather text content from XML from what I could see. (I'd gladly take pointers, though)
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
}
There is -- as always -- a difference between the W3 adherent browsers and IE. The W3 compliant browsers expose the Node#textContent property, while IE exposes the Node#innerText property.
MDN documentation for Node#textContent
HTH,
FK
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.
$html = $("<!-- comment --> <p>text</p>");
creates a jQuery collection like so
$( [the comment], [text node], p )
How can I access the paragraph only? .find("p") returns an empty collection
And, for extra points,
$html = $("<p>text</p>");
creates a jQuery collection like so
$( p )
Is there a fail safe way to get at the p, and only the p, that works whether the comment is there or not?
The simplest way is with filter and the universal selector *, which matches all elements.
$html = $("<!-- comment --> <p>text</p>").filter('*');
var p = $html.filter(function() { return this.nodeType === 1; });
jsFiddle.
Try this demo. Maybe this is not exactly how you're gonna use it, but you get the point.
<div class="text">
<!-- comment -->
<p>text</p>
</div>
var html = $('.text').html();
html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
alert(html);
One way is to get by index like in $html = $("<!-- comment --> <p>text</p>"); you can get p tag using $($html[2]).
OR
$html = $("<!-- comment --> <p>text</p>");
$target = new Object();
for(key in $html){
if(typeof $html[key] === 'object' && $html[key].localName === 'p')
$target = $html[key];
}