我的目标很简单,我只需要通过属性获得值。例如,考虑以下xml:
<?xml version="1.0" encoding="UTF-8"?>
<preferences>
<custom-preferences>
<staging>
<preference preference-id="foo">true</preference>
<preference preference-id="bar">true</preference>
</staging>
<custom-preferences>
<preferences>
</xml>
xml在一个文件中,这是我目前所得到的:
var fs = require('fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
fs.readFile(pref, function(err, data) {parser.parseString(data, function (err, result) {
console.log(result.preferences['custom-preferences'][0].staging[0].preference[0]);
});
});
因此,如果我硬编码索引,它将工作,但我可以选择节点,其中preference-id = foo或bar等
我试图避免读取父节点并为每个执行a。我很乐意使用其他包或库,如果它能帮助我实现目标。
可以通过jsdom或xml.etree.ElementTree
代码由node.js编写
const jsdom = require("jsdom");
const response = `
<?xml version="1.0" encoding="UTF-8"?>
<preferences>
<custom-preferences>
<staging>
<preference preference-id="foo">true</preference>
<preference preference-id="bar">true</preference>
</staging>
</custom-preferences>
</preferences>`
const dom = new jsdom.JSDOM(response);
console.log('foo: ' + dom.window.document.querySelector('[preference-id="foo"]').textContent)
console.log('bar: ' + dom.window.document.querySelector('[preference-id="bar"]').textContent)
结果
$ node find-attribute.js
foo: true
bar: true
Python编写的代码
import xml.etree.ElementTree as ET
document = """
<?xml version="1.0" encoding="UTF-8"?>
<preferences>
<custom-preferences>
<staging>
<preference preference-id="foo">true</preference>
<preference preference-id="bar">true</preference>
</staging>
</custom-preferences>
</preferences>
"""
root = ET.fromstring(document)
print("preference-id='foo' " + root.find(".//*[@preference-id='foo']").text)
print("preference-id='bar' " + root.find(".//*[@preference-id='bar']").text)
结果
$ python find-attribute.py
preference-id='foo' true
preference-id='bar' true