简体   繁体   English

使用JavaScript从XML字符串中提取值

[英]Extract a value from an XML string using JavaScript

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. 给我一个XML字符串和一条消息(字符串),我需要一个函数,该函数可以解析XML字符串并返回存在消息的XML标签(id =“ x”)的ID数组。

I can only use JavaScript for this. 我只能为此使用JavaScript。

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

First parse the XML into a DOM: see for example Parse XML using JavaScript 首先将XML解析为DOM:例如, 使用JavaScript解析XML

Then, on the resulting DOM Document object, execute the XPath expression 然后,在生成的DOM Document对象上,执行XPath表达式

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

This will return a set of attribute nodes. 这将返回一组属性节点。

Depending on what might be in the xml you don't necessarily have to parse it. 根据xml中的内容,您不必解析它。 You might get away with just searching it for id="number" 您可能仅通过搜索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. 或者在第一行匹配整个标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM