解析XML Libxmljs(Node.js) [英] Parse XML Libxmljs (Node.js)

查看:82
本文介绍了解析XML Libxmljs(Node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 libxmljs(https://github.com/polotek/libxmljs)解析XML字符串.我遇到了一些问题.我需要对要解析的内容应用逻辑,并根据定义的内容和未定义的内容返回逻辑.因此,我看不到SAX样式的解析器是有效的选项.

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.

如果我能实现想要的目标,我愿意考虑其他选择.能够选择DOMParser xmlDoc.getElementsById('firstName')[0].childNodes[0].nodeValue之类的元素真是棒极了...

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...

推荐答案

libxmljs支持DOM以及SAX样式解析.

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');

该API是自定义的,不符合W3C/浏览器规范(在我的列表中).您将需要使用xpath在文档中查询所需的内容.

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()

请注意,childNodes和text是函数调用.看一下文档.

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

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

据我所知,libxmljs和jsdom是两个具有不错的DOM实现的库.

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

这篇关于解析XML Libxmljs(Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆