Set new Attribute in XML using jQuery

If you want to add new attribute in XML using jQuery. Let’s check how to do this using below sample xml.

<section marked="marked"></section>

You can add attribute in any XML tag as you add in case of HTML. First your XML is saved in any variable like given below.

var a = '<data><section></section></data>';
a = $(a);
a.find('section').attr('marked', 'marked');   

/// Above line will add an attribute in section tag.

One more example:

You will call “SetAttribute” method (given below) to add attribute in given XML. Please check below the syntax as shown below:

SetAttribute("marked", "marked",FullXmlAsString,"section" ) 
var SetAttribute = function (id, value, sourceXML, specificNode) {
        //param :id,  id of XML node.
        //param : value, value of the new node.
        //param :sourceXML, it is the complete XML text  in which node need to be added.
        //param :specificNode, it is the name of node which will get addded in above complete XML and  then final text will get returned. 
        var test = "";
        var xmlDoc = $.parseXML(sourceXML);
        $xml = $(xmlDoc);
        if (specificNode === undefined || specificNode === "") {
            test = $xml.attr(id, value); //will add prpty at root
        } else {
            //var test = $xml.find('section').attr('marked', 'marked');
            test = $xml.find(specificNode).attr(id, value);
        sourceXML = test[0].outerHTML;
        return sourceXML;

Leave a Reply

Your email address will not be published. Required fields are marked *