0
我想解析下面的示例XML文件,以獲取一些數據。下面是XML文件:nodejs elementtree npm xml解析
<Benchmark xmlns="http://checklists.nist.gov/xccdf/1.1" xmlns:xsi="www.w3.org/2001/XMLSchema-instance" id="SAP-HANA" resolved="1" xml:lang="en-US">
<status date="2016-03-17">draft</status>
<title xmlns:xhtml="http://www.w3.org/1999/xhtml" xml:lang="en-US">Guide to the Secure Configuration of SAP HANA</title>
<version>0.1.28</version>
<Profile id="profile1">
<title xmlns:xhtml="http://www.w3.org/1999/xhtml" xml:lang="en-US">text1</title>
<select idref="This is rule 1" selected="true"/>
<set-value idref="ssfs_master_key_timeout">20</set-value>
</Profile>
<Profile id="profile2">
<title xmlns:xhtml="http://www.w3.org/1999/xhtml" xml:lang="en-US">text2</title>
<select idref="this is rule1" selected="true"/>
<select idref="this is rule1" selected="true"/>
<select idref="this is rule1" selected="true"/>
</Profile>
</Benchmark>
從我需要得到所有配置文件(配置文件1,PROFILE2 ...),然後爲每個配置文件的標題標籤,我需要得到它的文本內容,此XML文件。我想才達到服用點是這樣的:下面
for all profile in XML{
get its attribute "id".
get its <title> tag's text content.
}
例如是預期的輸出:
profile1
text1
profile2
text2 // but in my code, it is always coming text1. I am not aware of, how to place [i]
我能夠得到的ID。但無法獲取標籤的文字內容。下面是我的代碼:
var fs = require('fs');
var et = require('elementtree');
var XML = et.XML;
var ElementTree = et.ElementTree;
var element = et.Element;
var subElement = et.SubElement;
var data, etree;
data = fs.readFileSync('my.xml').toString();
etree = et.parse(data);
var length = etree.findall('./Profile').length;
for (var i = 0; i < length; i++) {
console.log(etree.findall('./Profile')[i].get('id'));
console.log(etree.findtext('./Profile/title')); // dont know, where to place [i]
// var profile = etree.findall('./Profile')[i].get('id');
// console.log(etree.findtext('./Profile'[@id=’profile’]'/title'));
//console.log(etree.findall('./Profile'[i]'/title'));
//console.log(list[i]);
}
嗨安東尼奧,謝謝你的迴應。有效。 :) –
@HemantYadav歡迎:) –
嗨安東尼奧,我遇到了elementTree模塊更多的問題。你可以請建議任何好的nodejs模塊的問題在下面的鏈接問。以後我可能需要進一步深入XML解析。我可能會再次遇到問題。或者elemenTree模塊的任何好的文檔。 http://stackoverflow.com/questions/42553153/nodejs-elementtree-npm-xml-parsing-and-merging –