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);