Parse XML Libxmljs (Node.js)

不羁岁月 提交于 2020-01-01 02:34:11

问题


I'm attempting to parse an XML string with libxmljs (https://github.com/polotek/libxmljs). I'm having some issues though. I need to apply logic to what I'm parsing and return based upon what's defined and what isn't. Because of this I don't see a SAX-style parser being a valid option.

I'm willing to look at other alternatives if I can achieve what I'm looking for. Being able to select elements like DOMParser xmlDoc.getElementsById('firstName')[0].childNodes[0].nodeValue would be awesome...


回答1:


libxmljs supports DOM as well as SAX style parsing.

var xmlDoc = libxmljs.parseXmlString('<item><data id="firstName">Your Name</data></item>');
var xmlDoc2 = libxmljs.parseXmlFile('mydata.xml');

The API is custom and doesn't follow the W3C/browser spec (it's on my list). You will want to use xpath to query the document for the content you want.

xmlDoc.find("//[@id='firstName']")[0].childNodes()[0].text()

Notice that childNodes and text are function calls. Take a look at the docs.

https://github.com/polotek/libxmljs/wiki/Element

As far as I know, libxmljs and jsdom are the two libraries that have decent DOM implementations.



来源:https://stackoverflow.com/questions/4190952/parse-xml-libxmljs-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!