I want to getElementsByTagName in xml file.
It is my code(.html).
<html>
<header>
<title>Read XML</title>
</header>
<body>
<h1>Hello My Application</h1>
<script type="text/javascript">
function readXML()
{
var xml= new XMLHttpRequest();
xml.open('GET', 'C:\Users\xxx\Testxml.xml');
//xml.send();
var xmlData = xml.responseText;
if(!xmlData)
{
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var emp = xmlData.getElementsByTagName("employee");
var name= emp[0].getElementsByTagName("name")[0].firstChild.data;
document.write("Name = " + name);
}
}
</script>
<button onclick="readXML()">Read XML File</button>
</body>
</html>
I run filename.html but there is error on line var name= emp[0].getElementsByTagName("name")[0].firstChild.data;
It is my xml file.
<company>
<employee>
<name>Chrish</name>
<age>40</age>
<salary>100</salary>
</employee>
</company>
Could you help me please?
Have you tried logging your xmlData variable to see if you are actually able to read the xml file? Because, as far as I know, reading local xml files in javascript is not allowed directly. You can try reading it through the File API. Read more about it here.
And secondly, your if condition seems incorrect. You are checking for (!xmlData) which means it will run when xmlData is empty while it should be running when you are actually able to get data in xmlData variable.
Related
I'm using the JSONEditor (https://github.com/josdejong/jsoneditor) to load a json file, make changes and save the file. This works great but it only saves the JSON file to the folder specified according to your browser settings. Here's the demo code (https://github.com/josdejong/jsoneditor/blob/master/examples/04_load_and_save.html):
<!DOCTYPE HTML>
<html>
<head>
<title>JSONEditor | Load and save</title>
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<script src="https://bgrins.github.io/filereader.js/filereader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<style>
html, body {
font: 11pt sans-serif;
}
#jsoneditor {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<h1>Load and save JSON documents</h1>
<p>
This examples uses HTML5 to load/save local files.
Powered by FileReader.js and
FileSaver.js.<br>
Only supported on modern browsers (Chrome, FireFox, IE10+, Safari 6.1+, Opera 15+).
</p>
<p>
Load a JSON document: <input type="file" id="loadDocument" value="Load"/>
</p>
<p>
Save a JSON document: <input type="button" id="saveDocument" value="Save" />
</p>
<div id="jsoneditor"></div>
<script>
// create the editor
var editor = new JSONEditor(document.getElementById('jsoneditor'));
// Load a JSON document
FileReaderJS.setupInput(document.getElementById('loadDocument'), {
readAsDefault: 'Text',
on: {
load: function (event, file) {
editor.setText(event.target.result);
}
}
});
// Save a JSON document
document.getElementById('saveDocument').onclick = function () {
// Save Dialog
fname = window.prompt("Save as...");
// Check json extension in file name
if(fname.indexOf(".")==-1){
fname = fname + ".json";
}else{
if(fname.split('.').pop().toLowerCase() == "json"){
// Nothing to do
}else{
fname = fname.split('.')[0] + ".json";
}
}
var blob = new Blob([editor.getText()], {type: 'application/json;charset=utf-8'});
saveAs(blob, fname);
};
</script>
</body>
</html>
I want to be able to save the file to the web server. Is there any way for me to save the edited JSON file to the web server? I searched and tried to integrate this library with JSONEditor but no joy:
https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
I'm not restricted to ajax so I'll consider anything that works!
Thanks for your advice.
John
UPDATED: Here's the controller code chunk.
// POST api/values
public async void Post()
{
string json = await Request.Content.ReadAsStringAsync();
File.WriteAllText(
HttpContext.Current.Server.MapPath("~\\App_Data\\somefile.json"),
json
);
}
I tested this using Postman and it works. What I can't seem to do for the life of me is to now send the edited JSON file to the controller. Here's the modified HTML page where I try unsuccessfully to send the json. For brevity, I'll just add the extra/edited code code:
<form id="form1" method="post" enctype="text/plain" action="http://localhost:1651/api/values">
<input type="file" name="json" id="loadDocument" value="Load"/>
<input type="submit" value="Save" />
</form>
Edited javascript where I try to return the edited json to the form:
document.getElementById('saveDocument').onclick = function () {
return editor.getText();
};
Please help! How do I send the json to the controller?
I am currently trying to build an HTML form with input fields to read an XML file and write back with changes. The first step is retrieving values on page load into the input fields but it doesn't want to work
<body>
<h1>Config Page</h1>
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
<b>Site Collection:</b> <span id="siteCollection"></span><br>
</div>
<script>
var xmlhttp, xmlDoc;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Configuration/config.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElement
document.getElementById("siteURL").value.innerHTML =
xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue;
document.getElementById("siteCollection").innerHTML =
xmlDoc.getElementsByTagName("siteCollection")[0].childNodes[0].nodeValue;
function myFunction() {
alert(siteURL + "is the site Url")
}
</script>
<button onclick="myFunction()">Get message value</button>
I know the XML is pulling through ok because the siteCollection span item works, but the input field does not.
Any help would be much appreciated.
Thank you.
Maybe if you use jQuery you can do it as following
http://codepen.io/Daethe/pen/dXWjJo
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
</div>
<button onclick="myFunction()">Get message value</button>
<script>
function myFunction() {
var xmlHttp = jQuery.parseXML('<?xml version="1.0" encoding="utf-8"?><config><siteURL>http://localhost/</siteURL></config>');
var xmlDoc;
xmlDoc = xmlHttp.documentElement;
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
</script>
Thanks to Daethe for putting me on the right track. I found my solution to read an xml file into a HTML input field form
for the javascript...
var xmlpath = "../configuration/test.xml"
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlpath, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
function loadFunction() {
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
For the page...
<script src="/Script/form.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<html>
<br>Site URL (EG: http://intranet)</br>
<input type="text" id="siteURL" name="siteURL" value="blank..." />
<button onclick="loadFunction()">Load Configuration</button>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<title>Please Check Data</title>
<script type="text/javascript">
function readXMLFile() {
var i;
var xml = new XMLHttpRequest();
xml.open('GET', 'projectRelatedData.xml', false);
xml.send();
var xmlData = xml.responseXML;
xmlData=(new DOMParser()).parseFromString(xml.responseText,'text/xml');
var projectData=xmlData.getElementsByTagName("project");
//alert(projectData.length);
for(i=0;i<projectData.length;i++)
{
var name=projectData[i].getElementsByTagName("name")[0].firstChild.data;
var imageName=projectData[i].getElementsByTagName("imagePath")[0].firstChild.data;
var pdfName=projectData[i].getElementsByTagName("pdfPath")[0].firstChild.data;
var description=projectData[i].getElementsByTagName("description")[0].firstChild.data;
var amount=projectData[i].getElementsByTagName("amount")[0].firstChild.data;
//alert("number of Project : "+projectData.length);
document.write(name+'<br>');
document.write(imageName+'<br>');
document.write(pdfName+'<br>');
document.write(description+'<br>');
document.write(amount+'<br>');
}
}
</script>
</head>
<body>
<button onclick="readXMLFile()">Click</button>
<p id="ccc"></p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<projectWebsite>
<project>
<name>CARGO SHIPPING</name>
<imagePath>CARGOSHIPPING.PNG</imagePath>
<pdfPath>cargoShipping.pdf</pdfPath>
<description>
Cargo shipping is all about booking cargo to move from one place to another. Owner can add new shipsand he can also track ships.User can register for cargo and he can also track ships.Admin has the right to view detailsof owner, to add a new company and also update price of ship. This software hasa very nice GUI to give a very nice presentation of a cargo management system.
</description>
<amount>4000</amount>
</project>
<project>
<name>E-BAZZAR</name>
<imagePath>ebazzar.PNG</imagePath>
<pdfPath>eBazar.pdf</pdfPath>
<description>
This project emphasizes on taking bookings of pat ient in a web portal system.Patient can search for the doctor and book for appointment . Doctor can check and confirm appointment so patient can visit accordingly.Also admin is provided to add doctors in the portal,moreover customer list can be seen as well.
</description>
<amount>4000</amount>
</project>
</projectWebsite>
When I try to pass my Html into WebBrowser.DocumentText which include JS.
<script src="jquery\script.js"> </script>
It is same path with my executable. But when open in Winform, it is unable to find the 'script.js'..
But when you enter the full path of script, it is working.
StreamReader stringReader = new StreamReader(htmlFilename, Encoding.Default);
StringBuilder sb = new StringBuilder();
string temp;
while (!String.IsNullOrEmpty(temp = stringReader.ReadLine()))
{
sb.AppendLine(temp);
}
stringReader.Close();
return sb.ToString();
Eventually I read html into StringBuilder, and pass it to WebBrowser.DocumentText. Any other way to make it works without giving full path of the script?
You can give like this into your HTML document
<script type="text/javascript" src="../jquery\script.js"></script>
in HTML Page
<html>
<head>
<script type="text/javascript" src={Fullpath}></script>
</head>
<body>
</body>
</html>
in C#
string ScriptfullPath = Application.StartupPath.ToString()+"\\jquery\\script.js";;
string htmlContent;
using (StreamReader reader = new StreamReader(Application.StartupPath + \\JQuery\\sample.htm"))
{
htmlContent = reader.ReadToEnd();
}
htmlContent = htmlContent.Replace("{Fullpath}", ScriptfullPath);
Then your HTML document will use Script file with full path...
I am a novice to JavaScript programming with XML. I tried the following example from the book "Inside XML", but couldn't able to get it running.
Following is the HTML code with JavaScript:
<HTML>
<HEAD>
<TITLE>
Reading XML element values
</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function readXMLDocument()
{
var xmldoc, meetingsNode, meetingNode, peopleNode
var first_nameNode, last_nameNode, outputText
<!--xmldoc = new ActiveXObject("Microsoft.XMLDOM")-->
<!--xmldoc.load("meetings.xml")-->
parser=new DOMParser();
xmldoc=parser.parseFromString("meetings.xml","text/xml");
meetingsNode = xmldoc.documentElement
meetingNode = meetingsNode.firstChild
peopleNode = meetingNode.lastChild
personNode = xmldoc.getElementsByTagName("PEOPLE").lastChild
first_nameNode = personNode.firstChild
last_nameNode = first_nameNode.nextSibling
outputText = "Third name: " +
first_nameNode.lastChild.nodeValue + ' '
+ last_nameNode.lastChild.nodeValue
messageDIV.innerHTML=outputText
}
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<H1>
Reading XML element values
</H1>
<INPUT TYPE="BUTTON" VALUE="Get the name of the third person"
ONCLICK="readXMLDocument()">
<P>
<DIV ID="messageDIV"></DIV>
</CENTER>
</BODY>
</HTML>
Following is the XML code used:
<?xml version="1.0"?>
<MEETINGS>
<MEETING TYPE="informal">
<MEETING_TITLE>XML In The Real World</MEETING_TITLE>
<MEETING_NUMBER>2079</MEETING_NUMBER>
<SUBJECT>XML</SUBJECT>
<DATE>6/1/2002</DATE>
<PEOPLE>
<PERSON ATTENDANCE="present">
<FIRST_NAME>Edward</FIRST_NAME>
<LAST_NAME>Samson</LAST_NAME>
</PERSON>
<PERSON ATTENDANCE="absent">
<FIRST_NAME>Ernestine</FIRST_NAME>
<LAST_NAME>Johnson</LAST_NAME>
</PERSON>
<PERSON ATTENDANCE="present">
<FIRST_NAME>Betty</FIRST_NAME>
<LAST_NAME>Richardson</LAST_NAME>
</PERSON>
</PEOPLE>
</MEETING>
</MEETINGS>
But, when I run the code in Chrome, I get the following error:
Uncaught TypeError: Cannot read property 'nodeValue' of null
Please help me to resolve this issue. Thank you in advance.
I used Firefox with the firebug plugin to debug but you can use Chrome without any plugins. After loading the page you can press F12 to open the devtools. In the console tab you can see the output of your logs, warnings, errors and there is a command line to execute JavaScript.
Sometimes I make a variable global (check in the code for variable a) so I can type a. in the command line and see what properties it has.
One of the problems was that a node includes whitespace so the last node is a textNode containing whitespace in many cases. You should also try to end your statements with ;
Here is the code half debugged, hope it helps:
<textarea id="txt">your xml content</textarea>
function readXMLDocument(){
var xmldoc, meetingsNode, meetingNode, peopleNode,
first_nameNode, last_nameNode, outputText;
<!--xmldoc = new ActiveXObject("Microsoft.XMLDOM")-->
<!--xmldoc.load("meetings.xml")-->
parser=new DOMParser();
xmldoc=parser.parseFromString(
document.getElementById("txt").value,"text/xml");
meetingsNode = xmldoc.documentElement;
meetingNode = meetingsNode.firstChild;
console.log("meetingNode is:",meetingNode);
peopleNode = meetingNode.lastChild;
console.log("peoplenode is:",peopleNode);
//use console.log to figure out what the variable could be
console.log(xmldoc.getElementsByTagName("PEOPLE"));
//set a global variable named a to the what you want to inspect
//in the commandline you can type a. and after the dot the devtools
//will produce a list of attributes.
a = xmldoc.getElementsByTagName("PEOPLE");
personNode = xmldoc.getElementsByTagName("PEOPLE")
.item(0).lastElementChild;
a = personNode;
//in the commandline I can see a.lastChild is textnode
//the intellisense gives me an option lastElementChild
//didn't look it up but it could be Firefox specific
first_nameNode = personNode.lastElementChild;
last_nameNode = first_nameNode.nextSibling;
console.log("there are still some things to fix:",
meetingsNode, meetingNode, peopleNode,
first_nameNode, last_nameNode);
return;
outputText = "Third name: " +
first_nameNode.lastChild.nodeValue + ' '
+ last_nameNode.lastChild.nodeValue;
}
readXMLDocument();
First let me thank you for the assistance, I am new to Javascript, and want to learn to parse a >.xml file into my javascript. The file I want to parse is contact.xml, located in my root folder.
Again, thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
<title>Contacts</title>
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
document.write("<div style='width:450px;'>")
document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+ "</p>");
document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue +"</p>);
document.write("</div>")
}
</script>
</body>
</html>
*Here is my .xml file*
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066"
email="customerservice#fsig.com"
url="http://www.fsig.com"
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>
You need to go down the hierarchy, so, first find the Contacts node, then inside there you can get all the tagnames as you have.
You have a great deal of attributes so you may find this useful also:
node.attributes["url"].nodeValue
So just loop through all the items, then I would just copy itemelem[t] to node just to make it easier, then you get the attributes you need.
Depending on the browser you are using most of them come with some javascript debugger, so you can put in breakpoints and look at the values in the variables and see what the next step needs to be.