Is there a way to get the name of an attribute of an XML node using javascript.
Lets take this as a sample XML
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Count name="EmployeeCount">100</Count>
<employee id="9999" >Harish</employee>
<Salary>
<year id="2000">50 Grands</year>
<year id="2001">75 Grands</year>
<year id="2002">100 Grands</year>
</Salary>
</Employees>
I am loading XML using ActiveXObject.As you can see not all elements have attributes.I need to list all attributes like
name
id
id
id
id
Try this:
var nodes = xml.selectNodes("//#*")
for(var i=0; i < nodes.length; i++)
{
alert(nodes[i].nodeName);
}
Related
My xml looks like this, I am able to retrieve the items and get the data from nodes like <title>, <description>. How to get the values from <media:title> and <media:credit>, <media:thumbnail>
This is how am able to get the data
var xmlparser = new DOMParser();
var xmlData = xmlparser.parseFromString(data.text(), "text/xml");
var items = xmlData.getElementsByTagName('item');
for(var i = 0; i < items.length; i++){
var title = items[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var desc = items[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
}
<pre xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
<Channel>
<item>
<title>List of records</title>
<description>reading xml</description.
<media:title xmlns:media="http://search.yahoo.com/mrss/">
SinkorSwim Trailer
</media:title>
<title>Sink or Swim - Trailer</title>
<description>Jon Bowermaster's documentary</description>
<media:description xmlns:media="http://search.yahoo.com/mrss/">
Jon Bowermaster's documentary on a learn-to-swim camp
</media:description>
<media:credit xmlns:media="http://search.yahoo.com/mrss/" role="Director"
scheme="urn:ebu">
Jon Bowermaster
</media:credit>
<media:status xmlns:media="http://search.yahoo.com/mrss/" state="active"/>
<media:thumbnail xmlns:media="http://search.yahoo.com/mrss/"
type="landscape" url="http://snagfilms-video.jpg"/>
<media:player xmlns:media="http://search.yahoo.com/mrss/" height="323"
url="http://embed.snagfilms.com/embed/player?filmId=00000158-b20c-d8f9-
affd-b32ce8700000" width="500"/>
</item>
<item></item>
<item></item>
</channel>
</pre>
The media in media:title denotes an XML namespace prefix. The namespace prefix is only a shortcut for the namespace. The namespace has to be defined somewhere in the document with an xmlns:media attribute.
Then you can use the namespace aware getElementsByTagNameNS() function to query for the title element:
console.log(xml.getElementsByTagNameNS('xmlns:media="http://search.yahoo.com/mrss/"', 'title'));
first parameter you have to pass the namespace name and not the prefix.
I'm trying to display data from the xml file by first getting the content of the xml file and storing it in XML DOM. Once the DOM object is created it is then parsed. I used a for loop so as to get data from each child node of the parent node but somehow only the second node's data is showing.
This is the code where the error is:
xmlhttp.open("GET","company.xml", false); //sets the request for calling company.xml
xmlhttp.send(); //sends the request
xmlDoc = xmlhttp.responseXML; //sets and returns the content as XML DOM
//parsing the DOM object
var employeeCount = xmlDoc.getElementsByTagName("Employee");
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
The XML file:
<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<Nickname>Tania</Nickname>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>
This the output:
How can i display the data from node [0] as well? Any suggestions will be appreciated. Thanks.
The problem is that you're overwriting data from previous Employee on every iteration :
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
That's why only the last Employee data remains in innerHTMLs in the end.
I am fetching an XML response from an external tool using
var myXML = api.path("item/"+itemId+"/metadata").dataType("xml").get();
The XML structure I receive this way looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MetadataListDocument xmlns="http://xml.vidispine.com/schema/vidispine">
<item id="VX-3594">
<metadata>
<revision>VX-61522,VX-61520,VX-61519,VX-61515,VX-61513,VX-61514,VX-61525,VX-61523</revision>
<group>Final Cut Server</group>
<timespan start="-INF" end="+INF">
<field uuid="2913190d-635c-4f81-951c-4ff3f934a547" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">
<name>shapeTag</name>
<value uuid="2c8b57d0-5c47-49c9-a4f0-54f7fef803cc" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">lowres</value>
<value uuid="6d994b0c-9d91-4b32-8052-824b3467a29e" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">original</value>
<value uuid="85cd07b7-6f13-4f6c-86fa-e42db20860c0" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">house_format_audio_through</value>
</field>
<field uuid="e2b4ca3c-6765-4890-99f4-f6e0624099eb" user="admin" timestamp="2015-03-16T16:47:57.506+01:00" change="VX-61513">
<name>portal_mf129489</name>
<value uuid="ab60ed17-75f4-4593-b068-9d8b6a700025" user="admin" timestamp="2015-03-16T16:47:57.506+01:00" change="VX-61513">no</value>
</field>
</timespan>
</metadata>
</item>
</MetadataListDocument>
Now I need to extract the value of the field with the name portal_mf129489, which in this case would be no.
To extract data from the xml output I already set the default name space:
default xml namespace = "http://xml.vidispine.com/schema/vidispine";
and I can extract things using
var myTimespan = myXML.item.metadata.timespan;
My question though is, how can I find a field element, which has a child element named portal_mf129489? If I find this element, I would need to fetch the value of the field's child element named value.
Each XML has multiple field elements, and inside the field I am looking for, name is always the first child element, value is always the second element.
Any ideas?
You can do this with little help of jQuery. The idea is to use jQuery to query XML document:
var xml = $.parseXML('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><MetadataListDocument xmlns="http://xml.vidispine.com/schema/vidispine"><item id="VX-3594"><metadata><revision>VX-61522,VX-61520,VX-61519,VX-61515,VX-61513,VX-61514,VX-61525,VX-61523</revision><group>Final Cut Server</group><timespan start="-INF" end="+INF"><field uuid="2913190d-635c-4f81-951c-4ff3f934a547" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523"><name>shapeTag</name><value uuid="2c8b57d0-5c47-49c9-a4f0-54f7fef803cc" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">lowres</value><value uuid="6d994b0c-9d91-4b32-8052-824b3467a29e" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">original</value><value uuid="85cd07b7-6f13-4f6c-86fa-e42db20860c0" user="system" timestamp="2015-03-16T16:52:48.061+01:00" change="VX-61523">house_format_audio_through</value></field><field uuid="e2b4ca3c-6765-4890-99f4-f6e0624099eb" user="admin" timestamp="2015-03-16T16:47:57.506+01:00" change="VX-61513"><name>portal_mf129489</name><value uuid="ab60ed17-75f4-4593-b068-9d8b6a700025" user="admin" timestamp="2015-03-16T16:47:57.506+01:00" change="VX-61513">no</value></field></timespan></metadata></item></MetadataListDocument>');
var value = $(xml).find('field > name').filter(function(){ return $(this).text() === 'portal_mf129489' }).siblings('value').text();
$('body').append(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Okay, got it working, now. I added the function:
function getField(ts, name) {
for (var i = 0; i < ts.field.length(); i++) {
var f = ts.field[i];
if (f.name == name) {
return f;
}
}
}
and this:
var r = api.path("item/"+itemId+"/metadata").dataType("xml").get();
var metadata = r.item[0].metadata;
var ts = metadata.timespan[0];
var tag = getField(ts, 'portal_mf129489');
if (tag && tag.value) {
logger.log('value: '+tag.value[0]);
}
I am currently working with Jquery and my entire project needs to be done only using sharepoint Client Object Model (so i cant make use of server side coding). I have created a xml structure (by appending some string together) and stored it in a jquery var variable. Now my variable content looks like this
<Collection xmlns="http://schemas.microsoft.com/collection/metadata/2009"
xmlns:ui="http://schemas.microsoft.com/livelabs/pivot/collection/2009"
SchemaVersion="1" Name="listname">
<FacetCategories>
<FacetCategory Name="Title" Type="String" />
<FacetCategory Name="Created By" Type="String" />
<FacetCategory Name="Modified By" Type="String" />
</FacetCategories>
<Items ImgBase="http://460d87.dzc">
<Item Id="0" Img="#0" Name="Name1" Href="http://site/1_.000">
<Facets>
<Facet Name="Title">
<String Value="Name1" />
</Facet>
</Facets>
</Item>
</Items>
</collection>
I want to convert this variable in to xml content purely based on jquery.I have used ParseXml() Method but i'm not able to see the output in alert(). Please help me out with this.
Just use native built-in XML parser:
var parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
}
var nodes = xml.getElementsByTagName('FacetCategory');
var i, l = nodes.length, items = [];
for (i = 0; i < l; i++) {
console.log(nodes[i].getAttribute('Name'));
}
http://jsfiddle.net/QqtMa/
Your xml is invalid, your root element is Collection but the closing tag is collection with small c, so the parser is failing
Sample XML.
<node>
<nodeid>28</nodeid>
<account_no xsi:nil="true" />
<address1>15 CANCUN CT</address1>
<serial_no>112199543</serial_no>
<x_lat>25.95513358000</x_lat>
<y_lon>-97.49027147000</y_lon>
<alarm>
<alarmid>Outage</alarmid>
<alarmtime>2012-07-30T14:46:29</alarmtime>
</alarm>
<alarm>
<alarmid>Restore</alarmid>
<alarmtime>2012-07-30T14:55:29</alarmtime>
</alarm>
</node>
<node>
<nodeid>67</nodeid>
<account_no>274192</account_no>
<address1>1618 CHIPINQUE DR</address1>
<serial_no>112199521</serial_no>
<x_lat>25.95286395000</x_lat>
<y_lon>-97.49323166000</y_lon>
<alarm>
<alarmid>Outage</alarmid>
<alarmtime>2012-07-30T14:46:29</alarmtime>
</alarm>
</node>
</ROOT>
I want to count the number of
<alarm>
elements the first node has as well as the second. I tried to do this in a for loop...
xmlDoc.getElementByTagName('alarm')[i].length;
this gives me all number of 'alarm' tags in the xml file. Which all i want is the current 'node' alarm elements. So here is what I want, I want for it to tell me the first has 2
<alarm>
tags and the second 'node' has 1
<alarm>
Just javascript no jQuery.
try this:
var nodes = xmlDoc.getElementsByTagName('node'), //Get the <node> tags
amountOfNodes = nodes.length
for(var i = 0; i < amountOfNodes; i++) { //loop thru the nodes
console.log(nodes[i].getElementsByTagName('alarm').length); //get the amount of <alarm> tags
}
EDIT
Here's a working example: Fiddle.
Tell me if that solves your problem :)