9

I have been using a DOMParser object to parse a text string to an XML tree. However it is not available in the context of a Web Worker (and neither is, of course, document.ELEMENT_NODE or the various other constants that would be needed). Is there any other way to do that?

Please note that I do not want to manipulate the DOM of the current page. The XML file won't contain HTML elements or anything of the sort. In fact, I do not want to touch the document object at all. I simply want to provide a text string like the following:

<car color="blue"><driver/></car>

...and get back a suitable tree structure and a way to traverse it. I also do not care about schema validation or anything fancy. I know about XML for <SCRIPT>, which many may find useful (hence I'm linking to it here), however its licensing is not really suitable for me. I'm not sure if jQuery includes an XML parser (I'm fairly new to this stuff), but even if it does (and it is usable inside a Worker), I would not include an extra ~50K lines of code just for this function.

I suppose I could write a simple XML parser in JavaScript, I'm just wondering if I'm missing a quicker option.

4

2 回答 2

7

根据规范

在本规范的这个版本中,工作人员无法使用 DOM API(节点对象、文档对象等)。

我想这就是为什么 DOMParser 不可用的原因,但我真的不明白为什么做出这个决定。(在 WebWorker 中获取和处理 XML 文档似乎不无道理)

但您可以导入其他可用工具:“JavaScript 中的跨平台 XML 解析”

于 2012-06-25T09:19:21.943 回答
6

在这一点上,我喜欢分享我的解析器:https ://github.com/tobiasnickel/tXml

使用它的 tXml() 方法,您可以将字符串解析为一个对象,并且它只需要 0.5kb 压缩 + gzipped

于 2015-04-07T09:11:11.137 回答