I am trying to create an xml document to send via a POST request. However, I am getting this error on the server side :
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.]
I think it may be because I am missing
<?xml version="1.0" encoding="UTF-8"?>
However I am unsure on the correct way to implement it. If anyone has any ideas that would great !
export function jsToXML(film, crudOp) {
//Creating Document and elements
var xmlDoc = document.implementation.createDocument(null, "film");
const xmlVersion = '<?xml version="1.0"?>';
var title = xmlDoc.createElement("title");
var year = xmlDoc.createElement("year");
var director = xmlDoc.createElement("director");
var stars = xmlDoc.createElement("stars");
var review = xmlDoc.createElement("review");
//Edit & Delete CRUD Operations need ID
if (crudOp === "edit" || crudOp === "delete") {
var id = xmlDoc.createElement("id");
id.append(film.id);
xmlDoc.documentElement.appendChild(id);
}
//Assign form data to elements
title.append(film.title);
year.append(film.year);
director.append(film.director);
stars.append(film.stars);
review.append(film.review);
//Append the elements to the xml doc
xmlDoc.documentElement.appendChild(title);
xmlDoc.documentElement.appendChild(year);
xmlDoc.documentElement.appendChild(director);
xmlDoc.documentElement.appendChild(stars);
xmlDoc.documentElement.appendChild(review);
return xmlDoc;
}
There's a very wide variety of possible causes: see org.xml.sax.SAXParseException: Content is not allowed in prolog for some of them. Omitting the XML declaration isn't one of those causes.
This is generally a message from the Java XML parser, so I'm not sure where your Javascript code (for constructing an XML tree) fits in.
To fix this I added a serializer as .createElement(Item), creates a HTML Node.
//Serialize xml dom
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
return xmlString;
This is what I added to solve the problem
Related
I'm having a hard time extracting presentationNotes from a keynote presentation using JXA (Javascript for osx) I don't want to use applescript. There is way more to this script than extracting notes.
It seems rather simple. However when I get the presentationNotes its in an RichText object that doesn't seem to have anyway to get normal text.
So I figured I'd open up textEditor and write them out to it.
Well I can't figure out how to do that.
var app = Application('Keynote')
document = app.documents[0]
slide_name = document.name()
i = 1 // loop through folder contents
folder_name = 'chapter'+i
//create a folder
var textEdit = Application('textEdit')
textEdit.activate()
var doc = textEdit.make({new:'document'})
doc.text = "fsdfsdfs"
var c = 0;
for(slide in document.slides){
var s = document.slides[slide]
var note = s.presentationNotes // returns object specifier
//textEdit.documents[0].push(note)
// I've tried lots of things here.
}
Any ideas or help would be appreciated. I've seen some applescript examples, however I couldn't get them to translate. Apparently applescript as text doesn't relate to toString()
You were almost there. You should not push the text, but push a paragraph object of the text.
Here is a complete example (text only).
It uses the currently open Keynote and TextEdit documents.
var Keynote = Application("Keynote");
var presentation = Keynote.documents[0];
var TextEdit = Application("TextEdit");
var document = TextEdit.documents[0];
document.paragraphs.push( TextEdit.Paragraph({color:"red", size:18}, "presentation: "+ presentation.name()+"\n" ))
for (var i=0; i<presentation.slides.length; i++) {
slide = presentation.slides[i];
slideTitle = slide.defaultTitleItem().objectText();
notes = slide.presenterNotes(); // text only
document.paragraphs.push( TextEdit.Paragraph({color:"blue", size:14}, "\n"+ (i+1) +": "+ slideTitle + "\n") )
document.paragraphs.push( TextEdit.Paragraph({}, notes +"\n") )
}
I am trying to read xml data and separate it by tag names so that I can save the values in variables for future use. But I am unable to read and filter the xml values. I need to read each value from the page given and seperate the tag values.
Following is my code-
I need to filter the data by CustomerID and find the particular email of the customer.
Can anyone help me please.
$.get("/read_xml.asp", function(XMLresponse) {
var xmldata=XMLresponse;
alert("Data Loaded: " + xmldata);
// Customers
alert(str.length);
var str =xmldata;
str = str.split('<CustomerID>');
str[1] = str[1].split('</CustomerID>');
alert(str[1]);
});
XML can be accessed like this (if it is valid):
var customerID = xmldata.getElementByTagName('CustomerID')[0].nodeValue;
like if it is a list:
for(var i = 0;i<xmldata.getElementByTagName('customer').length;i++){
var customer = xmldata.getElementByTagName('customer')[i];
var customerID = customer.getElementByTagName('CustomerID')[0].nodeValue;
}
As said in comments, one must see your XML that you receive from that ajax call.
However, to traverse your document or to find elements with jquery is obvious.
$(xml).find('ParentElement').each(function(){
var id = $(this).attr('CustomerID');
var title = $(this).find('CustomerTitle').text();
var other = $(this).find('CustomerOther').text();
});
You can use $.parseXML and then query the document like you would query the DOM using selectors.
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
xmlDoc = $.parseXML( xml ), //create a document from the XML string
$xml = $( xmlDoc ), //wrap the document in a jQuery object
$title = $xml.find( "title" ); //find every title tags
The example comes from the source I linked, but I added comments.
So here's the deal: I'm trying to retrieve a NodeList object from an already existing NodeList. Here's a simplified XML example:
<products>
<category>
<name>Category A</name>
<product>
<code>1</code>
<name>Product 1 Category A</name>
<price>10.0</price>
</product>
<product>
<code>2</code>
<name>Product 2 Category A</name>
<price>20.0</price>
</product>
</category>
<category>
<name>Category B</name>
<product>
<code>3</code>
<name>Product 1 Category B</name>
<price>5.0</price>
</product>
...
</category>
</products>
As you can see, the tag name appears twice, once as a child node of category and again as a child node of product. I wish to retrieve only product names. Since I can't read from the XML file but rather receiving it as a string, here's my parse function:
function parseXML(xmlString) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
var products = xmlDoc.getElementsByTagName("product");
var names = products.tags("name"); //Here's my problem
for(var i = 0; i < names.length; i++){
var element = names[i];
var name = element.firstChild;
$('#div_products').append(name.data + "<br>");
}
$('#div_main').html($('#div_products').html());
}
This is what I'm using as reference: http://help.dottoro.com/ljtrjxbf.php. Using nodeListObject.tags("tag"), however, will produce the following error:
processMessage failed: Stack: TypeError: Object #<a NodeList> has no method 'tags'
I've trying different approaches, but nothing worked. Even
var names = products["name"];
returns "undefined", which wouldn't work for me in any case, since the documentation says that aside from IE, it will return only the first node and
A) I'm working with Android/Cordova and
B) There's no attribute "name" in the node anyway.
So how do I work this out? I supposed I could try to create a new XMLDocument object from the products NodeList but I haven't looked into it since it must have a more trivial way to solve this problem.
Thank you Teemu, I've managed to achieve what I wanted with a few tweaks in my Javascript code. I'll post it here so that maybe someone might find it helpful in the future:
function parseXML(xmlString) {
var NAME = 5;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml");
var products = xmlDoc.getElementsByTagName("product");
for(var i = 0; i < products.length; i++){
var nodeList = produtos[i].childNodes;
$('#div_products').append(nodeList[NAME].textContent + "<br>");
}
$('#div_main').html($('#div_products').html());
}
Please notice that 5 is the index of the DOM TextNode I wanted (the product name itself), hence:
var NAME = 5;
That would be all.
UPDATE :
Some have said that they were able to get more than 1 childNode...
Here is my fiddle - I am only getting 1 childNode to display.
Where is the error?
ORIGINAL Question
Below is a partial snippet of javascript code that I have inherited. Basically this function used to get XML data by calling an AJAX function. However, due to requirement changes I am generating an XML string and storing that string in hidden input variable on the screen (Classic ASP).
After looking closer at the original script I found that it would be nice if I could somehow pass my xml string into the cmdxml variable. However, when I set cmdxml equal to my xml string: cmdxml = $.parseXML(xmlVal); and then try to use the snippet below it only gets 1 child node. I've included a small snippet of the xml string that I'm passing below.
Old Javascript Function (partial) using cmdxml:
if (req.responseXML!=null) {
var PropName;
var PropValue;
var cmdxml = req.responseXML.documentElement;
// read each document element child node in the XML document
for (var c =0;c<cmdxml.childNodes.length;c++) {
var m;
var t = cmdxml.childNodes[c]; //req.responseXML.documentElement.childNodes[c]
if (t!=null) {
//console.log(t.nodeName);
switch(t.nodeName) { //req.responseXML.documentElement.childNodes[c].nodeName
case "RObject": { //response object
var RObject = t;
//req.responseXML.documentElement.childNodes[c].nodeName.attributes[2].value
var CtrlChangeType = RObject.attributes[2].value;
var CtrlObjName = RObject.attributes[1].value;
var CtrlObjType = RObject.attributes[0].value;
var CtrlObj;
var RObjProp = RObject.getElementsByTagName("Property");
PropName = RObjProp[0].attributes[0].value;
PropValue = getElementText(RObjProp[0].getElementsByTagName("Value")[0]);
switch (CtrlChangeType) { //req.responseXML.documentElement.childNodes[c].nodeName.attributes[0].value
case "comboboxInsRow": {
Here is a snippet of my xml string that I'm passing:
<?xml version="1.0" ?><xCMDS><JCallBack ProgramName="x"><Value><![CDATA[top.closeCtrlLoading();]]></Value></JCallBack><RObject Type="E" Name="gH2ptObj_co_code" ChangeType="objProp" rowNum="" colNum=""><Property Name="value"><Value><![CDATA[]]></Value></Property></RObject>
parseXML returns an XMLDocument, . You'll need to set cmdxml zo $.parseXML('snippet').documentElement to access the childNodes(childNodes is a property of nodes, usually not available in documents) .
Your fiddle returns a childNode, but this is the root-element, you like to access the childNodes of the root-element.
I am new to XML and AJAX and am only a newcomer to Javascript and jQuery. Among other job duties I design our website. A deadline is very near, and the only way I can think of to do this project well is with AJAX. I have a document full of XML objects such as this one repeating:
<item>
<subject></subject>
<date></date>
<thumb></thumb>
</item>
I want to create an array of all elements and their child elements. I've been reading jQuery tutorials on AJAX for hours and don't even know where to start because they all assume a certain level of javascript proficiency. If someone could show me the easiest way to loop through all elements and put their children into an array, I'd appreciate it tons.
Using jQuery, $.ajax() your XML file, and on success pass retrieved data with each, like:
var tmpSubject, tmpDate, tmpThumb;
$.ajax({
url: '/your_file.xml',
type: 'GET',
dataType: 'xml',
success: function(returnedXMLResponse){
$('item', returnedXMLResponse).each(function(){
tmpSubject = $('subject', this).text();
tmpDate = $('date', this).text();
tmpThumb = $('thumb', this).text();
//Here you can do anything you want with those temporary
//variables, e.g. put them in some place in your html document
//or store them in an associative array
})
}
});
I wrote this.. pretty simple way to take a welformed XML response/string and parse it with jquery and then convert to array.
var response = '<?xml version="1.0" encoding="UTF-8"?><root><node1>something</node1></root>'
var xmlDoc = $.parseXML( response );
var myArray = getXMLToArray(xmlDoc);
alert(myArray['root']['node1']);
//Pop up window displaying the text "something"
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text();
}
});
}
return thisArray;
}
Hope this helps!!
If you are using jQuery then parseXML will suck an entire xml doc into a usable data structure.
I added to your script Troublesum
function getXMLToArray(xmlDoc){
var thisArray = new Array();
//Check XML doc
if($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner array
var NextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = [];
$(xmlDoc).children(this.nodeName).each(function(){
thisArray[this.nodeName].push($(this).text());
});
}
});
}
return thisArray;
}
It now also supports many children with same name in XML. f.e
XML being
<countries>
<NL>
<borders>
<country>Germany</country>
<country>Belgium</country>
countries.NL.borders[1] will give Germany.