1

I have this as XML:

<explination>
  <p>This is a great tool</p>
  <p>and i love it</p>
</explination>

And need to convert it to this as a string:

<p>This is a great tool</p>
<p>and i love it</p>

I am using this crazy converter which works if I pass the whole xml from my first code block.

But then I get that <explination> node in there, which I don't want. I could parse the string and remove that node, but I would rather not.

If I use $(xml).children() that returns me the following.

[<p>​This is a great tool​</p>​, <p>​and i love it​</p>​]

This is great, but then when I pass it to the crazy converter I mentioned earlier, it fails because it can't handle the array returned by children().

Is there a way to convert what gets returned by children() to standard xml? A $.toXml() method or something?

Any tips?

Thanks

Community
  • 1
  • 1
dezman
  • 18,087
  • 10
  • 53
  • 91

3 Answers3

1

Here's one way to do it using jQuery's $.parseXML() function:

var contentAsString = $($.parseXML(xml)).find("explination").html();

$.parseXML() returns an XML document, so if you feed that into $() you get back a jQuery object so then you can use jQuery traversal methods like .find() to get the element you care about and then take its content as a string including tags using .html().

Or for the particular xml input you show you can probably get away with pretending your xml is html and do this:

var contentAsString = $(xml).html();

Note that neither method needs your "crazy converter" at all.

"it fails because it can't handle the array returned by children()."

.children() doesn't return an array, it returns a jQuery object (which is array-like).

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • so im loading these xml docs via ajax, what dataType do you suggest i use? – dezman Dec 27 '13 at 06:13
  • I've tried both of your methods and html() always returns undefined. – dezman Dec 27 '13 at 06:16
  • I tested both methods before posting and both worked for me assuming that the `xml` variable contains a _string_. See: http://jsfiddle.net/uC9NE/ So if loading via ajax I guess `dataType:'text'` would be needed for the JS I've shown. If you use `dataType:'xml'` then you don't need `$.parseXML()` because jQuery will do that automatically before passing the result to your success handler. – nnnnnn Dec 27 '13 at 06:32
  • Your example has: Uncaught TypeError: Cannot call method 'replace' of undefined – dezman Dec 27 '13 at 06:40
  • Ah - in IE? I only tested it in Chrome and FF. Sorry. – nnnnnn Dec 27 '13 at 06:44
0

Provided that you want to extract the contents as a string, perhaps you could do something like this:

var doc = $($.parseXML(xml));
var content = $("<p>").append(doc.find("p").clone()).html();

Here is a fiddle to demonstrate: http://jsfiddle.net/23g6N/

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

I've tryed what you described, but the Jquery .html() function ignores the lowercase node characters. I needed something to parse an XML to a String in a case sensitive way, so I've developed next plugin my own. Copy next code to a file and save as a .js file.

/* 
 * THIS COMES WITH ABSOLUTELY NO WARRANTY.
 * 
 * This JQuery plugin just provides an easy way to parse an XML document object 
 * into a case sensitive string.
 * Self closing is not detected, and will be stringifyed as an empty xml node.
 * 
 * Tested in the following browsers:
 * -Chrome (v 33.0.1750.154 m)
 * -IE9 (v 9.0.8112.16421)
 * -Firefox (v 28.0)
 * -Opera (v 12.16)
 * -Safari (v 5.1.7 (7534.57.2))
 * 
 * @author Germán Coines Laguna - german.coines@hotmail.com
 * 
 * @usage $.fn.xmlToString(xmlObj)
 * @param xmlObj - An XML document object
 * @returns The Xml stringifyed.
 * 
 * @version 1.0
 * @depends JQuery v.1.9.1
 */
(function($){

  $.fn.xmltostring = function(xml)
  {
    var xmlText = "";

    $(xml).children().each(function(i,node){
      stringifyNode(node);
    });

    function stringifyNode(nd)
    {
      //obtain analisys obj
      var az = analyzeNode(nd);

      xmlText += "<" + az.nm + " " + az.ats + ">";

      if(az.chd) $(nd).children().each(function(i, ch){
        stringifyNode(ch);
      });

      xmlText += "</" + az.nm + ">";
    }

    function analyzeNode(nodeObj)
    {
      var obj = {nm: "", ats:"", chd: false, txt: ""};

      //Name
      obj.nm = nodeObj.nodeName;
      //Attributes
      $(nodeObj.attributes).each(function(i, at){
        obj.ats += at.name + "=\"" + at.value + "\" ";
      });
      //Children
      obj.chd = $(nodeObj).children().length > 0;
      //Text
      obj.txt = $(nodeObj).text();      

      return obj;
    }

    return xmlText;
   };  

 }(jQuery));

I haven't tested timmings for such huge XML files, but It did what I've required.

Hope It helps.

Here's an example on how to use it (Note you have to register the JQuery .js file, the file you saved with the code above, and replacing "yourPathToFile/yourFileName.xml" by your required values):

<script type="text/javascript" >

  $(document).ready(function(){

    var xml = loadXMLDoc("yourPathToFile/yourFileName.xml");

    alert($.fn.iwebxmltostring(xml));

    //var test = $.parseXML($("#result").text());

    //alert($(test).children().prop('nodeName'));

  });      

</script>

Good bye!