0

I am facing the following problem:

I am given a XML string and a message (string) I need a function that can parse the XML string and return an array of ids for the XML tags (id="x") in which the message is present.

I can only use JavaScript for this.

function getIdByMessage(xml, message) {
// problem to solve
}

var xml = `
<test>blabla</test>
<otherstuff>MoreStuff</otherstuff>
<message-not-relevant>Not relevant</message-not-relevant>
<entry id="4">Function Message<entry>
<otherstuff>MoreStuff</otherstuff>
<message-not-relevant>Not relevant</message-not-relevant>
<entry id="3">Function Message<entry>
<otherstuff>MoreStuff</otherstuff>
<message-not-relevant>Not relevant</message-not-relevant>
`

getIdByMessage(xml, 'Function Message'); // should return [4, 3];
floroz
  • 365
  • 2
  • 16

2 Answers2

0

Depending on what might be in the xml you don't necessarily have to parse it. You might get away with just searching it for id="number"

For example:

let matches = xml.match(/id="[\d]+"/gm);
let entryIds = matches.map(m => m.match(/\d+/)[0]));

Or match the whole tag on the first line.

  • That's generally bad advice. We get an awful lot of questions on StackOverflow saying, in effect, "I need to generate my XML in a very specific format because the recipient isn't using a proper XML parser to process it". – Michael Kay Mar 10 '19 at 15:26
  • If you have a schema, and you know that, say, only one tag comes with an id, or that the entry tag has only the id attribute, then you can formulate a regular expression that will match any XML file that matches the schema. So, if the entry tag is only present at one place in the schema, and can only have an id attribute then // isn't likely to fail. – Cobalt Chicken Mar 10 '19 at 20:57
  • You consider being "unlikely to fail" as good enough? How unlikely does it have to be? Your regex doesn't even allow the attribute to be in single quotes rather than double quotes. Regex solutions ALWAYS have that kind of bug; in fact computer science theory tells you that a regular expression CANNOT be written that always works, because XML is not a regular language. – Michael Kay Mar 11 '19 at 00:48
  • And if you don't believe that, here's an exercise: write a regex that will match `` *provided it hasn't been commented out*. – Michael Kay Mar 11 '19 at 00:52
  • Fair point. I've seen so many cases though where people have used a heavyweight tool where I lightweight one will do what is required, with far less effort. – Cobalt Chicken Mar 11 '19 at 08:37
0

First parse the XML into a DOM: see for example Parse XML using JavaScript

Then, on the resulting DOM Document object, execute the XPath expression

//entry[. = 'Function Message']/@id

This will return a set of attribute nodes.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164