0

I'm looking for a way to parse a string containing inline elements that can be picked up by javascript. An example.

Given the below parseable string:

"I have a <noun length="10" />

Is there any way to easily parse this string and understand that there is an object in that string called "noun" that contains a length property with a value of 10?

alex
  • 2,464
  • 23
  • 32
bash721
  • 140
  • 2
  • 10
  • 3
    [XML parsing of a variable string in JavaScript](http://stackoverflow.com/questions/649614/xml-parsing-of-a-variable-string-in-javascript)? – blex Jul 27 '14 at 20:32
  • ".. but rather a string that –"? Do you want a non-DOM approach? – dcromley Jul 27 '14 at 20:57
  • Why not just use jquery? – Blaskovicz Jul 28 '14 at 01:00
  • What is an "XML-like syntax"? HTML is 'XML-like', SGML language with enough `<` and `>` characters in is 'XML-like'. Without a clearer understanding of your syntax this is too broad to answer. –  Jul 28 '14 at 01:26

2 Answers2

0

You need to ensure that your string is well-formed XML. In this case, you need to ensure that there is a document element.

An example of how you can wrap the value in a <doc> element and then parse and query for the attribute value:

function parseSnippet(snippet, xpathExpression) {
    var startDoc = "<doc>",
        endDoc = "</doc>",
        xml = startDoc + snippet + endDoc,
        xmlDoc;

    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xml, "text/xml");
    } else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(xml);
    }
    return xmlDoc;
}
var xmlDoc = parseSnippet('I have a <noun length="10" />');
var nounLength = document.evaluate('/doc/noun/@length', 
                                   xmlDoc, 
                                   null,
                                   XPathResult.FIRST_ORDERED_NODE_TYPE, 
                                   null).singleNodeValue.textContent;

alert("length: " + nounLength);

Below is the same concept, but leveraging jQuery and the parseXML() function:

function parseSnippet(snippet) {
    var startDoc = "<doc>",
        endDoc = "</doc>",
        xml = startDoc + snippet + endDoc,
        xmlDoc = $.parseXML( xml );

    return $( xmlDoc );   
}
var $length = parseSnippet('I have a <noun length="10" />')
              .find( "noun" ).attr("length");

console.log("length: "+ $length);
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
-1

Would jquery work?

var a = $(string)
undefined
a.select("noun")
[
<noun attr=​"thing">​</noun>​
]
a.select("noun").attr("attr")
"thing"
Blaskovicz
  • 6,122
  • 7
  • 41
  • 50