首页 > 解决方案 > 为什么 libxmljs 无法解析 fs.readFile() 读取的数据?

问题描述

我想使用 XPath 过滤掉 XML 文件中的一些元素。我正在使用 node.js 的 fs 模块来读取 XML 文件并将读取的数据传递给 libxmjs 的 parseXml()。

fs 和 libxmljs 的版本

$ npm list libxmljs
`-- libxmljs@0.19.5

$ npm list fs
`-- fs@0.0.1-security

我的代码

var libxmljs = require('libxmljs');
var fs = require('fs');
var xmlref = fs.readFile('<filePath>','utf8',filterXmlContents);

function filterXmlContents(err,xml){
    console.log('Input XML:'+xml);
    //This prints the xml read by fs. It contains NodeOfInterest as well.
    var xmlDoc = libxmljs.parseXml(xml);
    var node = xmlDoc.get('//NodeOfInterest');
    //But here I get undefined.
    console.log(node);
    console.log(node.text());
}

不知道为什么libxmljs无法解析fs读取的内容?我试过了

xmlDoc.getChildNodes()

我得到

[ {}, {}, {}, {}, {} ]

有人可以帮我吗?谢谢。

PS 在我的代码中,libxmljs 的 parseXmlFile 不起作用。我明白了TypeError: libxmljs.parseXmlFile is not a function

标签: javascriptnode.jsnpmxml-parsing

解决方案


推荐阅读