PHP's SimpleXMLElement analog for Node.js

PHP's SimpleXMLElement analog for Node.js

本文关键字:analog for Node js SimpleXMLElement PHP      更新时间:2024-01-19

我使用过的最好的XML读写API是PHP的SimpleXMLElement。例如,要创建以下XML文本的DOM:

<root>
    <foo>
        <bar baz="goo">
            moo
        </bar>
    </foo>
</root>

在PHP中,人们只会写:

$root = new SimpleXMLElement('<root/>');
$root->foo->bar = 'moo';
$root->foo->bar['baz'] = 'goo';

读取XML的样式相同,添加了xpath()函数。

我听到人们称之为"建设者模式"。不太确定这是否合适。无论如何,Node.js下有没有API具有类似的易用性?

是的,它有jsdom。

jsdom允许您像在客户端上一样使用DOM。

如果裸DOM让您感到害怕,您甚至可以将jQuery与之结合使用。

文档示例:

// Run some jQuery on a html fragment
var jsdom = require('jsdom');
jsdom.env('<p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom''s Homepage</a></p>', [
  'http://code.jquery.com/jquery-1.5.min.js'
],
function(errors, window) {
  console.log("contents of a.the-link:", window.$("a.the-link").text());
});