I'm using this code to generate xml from my jqgrid's data:
var grid = $("#gridTable");
var dataFromGrid = grid.jqGrid ('getRowData');
var xml_string = '<rows>\n' + xmlJsonClass.json2xml ({rowTest:dataFromGrid}, '\t') +
'</rows>';
when the cell inside the grid is empty i get inside the xml tag "_EMPTY_STRING" ,
how can i change it to be just empty xml tag (like this: <cell1></cell1>)
while generating it ?
Thank's In Advance.
The most easy way to do this is just to append your code with the following line
xml_string = xml_string.replace(/>__EMPTY_STRING_<\//g, "><\/");
It will cut all __EMPTY_STRING_ strings.
Related
I am trying to get the text value of this a tag:
67 comments
so i'm trying to get '67' from this. however there are no defining classes or id's.
i've managed to get this far:
IEnumerable<HtmlNode> commentsNode = htmlDoc.DocumentNode.Descendants(0).Where(n => n.HasClass("subtext"));
var storyComments = commentsNode.Select(n =>
n.SelectSingleNode("//a[3]")).ToList();
this only give me "comments" annoyingly enough.
I can't use the href id as there are many of these items, so i cant hardcord the href
how can i extract the number aswell?
Just use the #href attribute and a dedicated string function :
substring-before(//a[#href="item?id=22513425"],"comments")
returns 67.
EDIT : Since you can't hardcode all the content of #href, maybe you can use starts-with. XPath 1.0 solution.
Shortest form (+ text has to contain "comments") :
substring-before(//a[starts-with(#href,"item?") and text()[contains(.,"comments")]],"c")
More restrictive (+ text has to finish with "comments") :
substring-before(//a[starts-with(#href,"item?")][substring(//a, string-length(//a) - string-length('comments')+1) = 'comments'],"c")
I am using ScrapySharp nuget which adds in my sample below, (It's possible HtmlAgilityPack offers the same functionality built it, I am just used to ScrapySharp from years ago)
var doc = new HtmlDocument();
doc.Load(#"C:\desktop\anchor.html"); //I created an html file with your <a> element as the body
var anchor = doc.DocumentNode.CssSelect("a").FirstOrDefault();
if (anchor == null) return;
var digits = anchor.InnerText.ToCharArray().Where(c => Char.IsDigit(c));
Console.WriteLine($"anchor text: {anchor.InnerText} - digits only: {new string(digits.ToArray())}");
Output:
I have an html file myfile.html, which includes a script with a line like this:
var json = '[{"name":"Hydrogen","number":"1","symbol":"H","weight":"1.00794"},{"name":"Helium","number":2,"symbol":"He","weight":4.002602},{"name":"Lithium","number":3,"symbol":"Li","weight":6.941},{"name":"Beryllium","number":4,"symbol":"Be","weight":9.012182},{"name":"Boron","number":5,"symbol":"B","weight":10.811},{"name":"Carbon","number":6,"symbol":"C","weight":12.0107}]';
The string within single quotes that is assigned to variable json will actually vary. I would like to replace this string with the entire contents of another file myjson.json.
I tried with the code here:
Find and replace in a file in Ruby
and here:
search and replace with ruby regex
doing this:
replace = File.read("myjson.json")
changefile = File.read("myfile.html")
changefile.sub( %r{var json = '[^<]+';}, replace )
but its not working. I'm not sure if its the regex I'm doing incorrectly, or if its something more.
UPDATE
After reading the reply below, my first attempt was:
replace = File.read("myjson.json")
changefile = File.read("myfile.html")
changefile.sub!(%r{var json = '.+'}, replace)
puts changefile
This did the find correctly, but removed all of the var json = '' and replaced it with myjson.json - I want to keep var json = and only replace the contents between the two single quotes after. So then I tried:
replace = File.read("myjson.json")
changefile = File.read("myfile.html")
changefile.sub!(%r{var json = '.+'}, "var json = 'replace'")
puts changefile
But that just replaced it with var json = 'replace'
I want to use the original var json = to find the location, but I don't want it to be removed.
So I did something I know is dumb and wrong, but it worked:
replace = File.read("myjson.json")
changefile = File.read("myfile.html")
changefile.sub!(%r{var json = '.+'}, "var json = 'thanksforthehelptinman'")
changefile.sub!(%r{thanksforthehelptinman}, replace)
puts changefile
Thanks for the help!
The regex isn't right because [ and ] are reserved in regex. You need to escape them:
%r{var json = '\[.+\]'}
I can't be more exact because I don't know what's in your JSON file, but that should get you into the ballpark.
Also, unless you assign changefile.sub to something, the substitution will be thrown away. You can do one of these two things:
changefile = changefile.sub(%r{var json = '\[.+\]'}, json)
or mutate changefile:
changefile.sub!(%r{var json = '\[.+\]'}, json)
Im loading an xml from stream
XDocument xmlFile = XDocument.Load(stream);
var query = from c in xmlFile.Elements("//Band") //error here
select c;
modify query....
Is it possible to find elements which are in format of Xpath ? (//Band) ?
p.s. I can use descendants but I want to ask about xpath....
Use the Descendants() method:
from c in xmlFile.Descendants("Band")
select c;
Or if you want to specify true XPath expressions, use the following Extensions:
XPathEvaluate()
XPathSelectElement()
XPathSelectElements()
I'm trying to get a list of tags from a particular tag group in Umbraco (v4.0.2.1) using the following code:
var tags = umbraco.editorControls.tags.library.getAllTagsInGroup("document downloads");
What I want to do is just output a list of those tags. However, if I output the variable 'tags' it just outputs a list of all tags in a string. I want to split each tag onto a new line.
When I check the datatype of the 'tags' variable:
string tagType = tags.GetType().ToString();
...it outputs MS.Internal.Xml.XPath.XPathSelectionIterator.
So question is, how do I get the individual tags out of the 'tags' variable? How do I work with a variable of this data type? I can find examples of how to do it by loading an actual XML file, but I don't have an actual XML file - just the 'tags' variable to work with.
Thanks very much for any help!
EDIT1: I guess what I'm asking is, how do I loop through the nodes returned by an XPathSelectionIterator data type?
EDIT2: I've found this code, which almost does what I need:
XPathDocument document = new XPathDocument("file.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("/tags/tag");
nodes.MoveNext();
XPathNavigator nodesNavigator = nodes.Current;
XPathNodeIterator nodesText = nodesNavigator.SelectDescendants(XPathNodeType.Text, false);
while (nodesText.MoveNext())
debugString += nodesText.Current.Value.ToString();
...but it expects the URL of an actual XML file to load into the first line. My XML file is essentially the 'tags' variable, not an actual XML file. So when I replace:
XPathDocument document = new XPathDocument("file.xml");
...with:
XPathDocument document = new XPathDocument(tags);
...it just errors.
Since it is an Iterator, I would suggest you iterate it. ;-)
var tags = umbraco.editorControls.tags.library.getAllTagsInGroup("document downloads");
foreach (XPathNavigator tag in tags) {
// handle current tag
}
I think this does the trick a little better.
The problem is that getAllTagsInGroup returns the container for all tags, you need to get its children.
foreach( var tag in umbraco.editorControls.tags.library.getAllTagsInGroup("category").Current.Select("/tags/tag") )
{
/// Your Code
}
I'm really new to using JSON to handle my Ajax Request and Response cycle. I've previously used just plain old parameters passed as POST data and I've rendered straight HTML in the response which was then placed into the DOM. As I've looked at various examples and read through various tutorials, it seems like a fairly common practice to simply build a string from the JSON object mixed with HTML that's been hard coded into the string and then assign the string as innerHTML to some element.
A common example looks something like this:
var jo = eval(req.responseText);
var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>';
$('myDiv').innerHTML = strTxt;
Is there a more elegant (or correct) way of handling the JSON response so that I'm not hard coding HTML in the javascript? Or is this pretty much how people do it?
P.S. Links to tutorials or other sources are appreciated.
I steer away from writing a lot of HTML within JavaScript strings. I prefer separation of structure from data manipulation. The better alternative is to place that code in the page, load the values based off the ID's, and show/hide it if necessary:
<div id="codeBlock" style="visible=false;">
<span id="val1"></span>
<br/>
<span id="val2"></span>
<br/>
</div>
............
<script>
var jo = eval(req.responseText);
$('val1').innerHTML = jo.f_name + ' ' + jo.l_name;
$('val2').innerHTML = 'Your Age Is: ' + jo.age;
$('codeBlock').show();
</script>
That might not be exactly what you want to do but you get the idea.
You could create the elements in the DOM using javascript instead of just dropping them into the innerHtml of the DIV, something like the following (untested):
var mySpan = document.createElement("span");
var spanContent = document.createTextNode(jo.f_name + ' ' + jo.l_name);
mySpan.appendChild(spanContent);
var myBr = document.createElement("br");
mySpan.appendChild(myBr);
var otherSpanContent = document.createTextNode('Your Age Is: ' + jo.age);
mySpan.appendChild(otherSpanContent);
mySpan.appendChild(myBr);
$('myDiv').appendChild(mySpan);
You could check out a templating engine such as PURE - may be a bit hard to get into at first but it supports many major javascript frameworks (and DOMAssistant which is nice) and separates html from the data.
The objects created from JSON are standard Javascript objects, therefore you can easily use jQuery selectors to create or access DOM elements and insert content from your JSON objects.
eg.
// Create a new span element and set its text
var personSpan=$("<span>").text(jo.f_name + ' ' + jo.l_name);
// Append the span to the existing myDiv element
$("myDiv").append(personSpan);
// Create a new div element (better then br) and set its text
var personDiv=$("<div>").text("Your Age Is: " + jo.age);
// Append the new div to the existing myDiv element
$("myDiv").append(personDiv);