首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nodejs elementtree npm xml解析

nodejs elementtree npm xml解析
EN

Stack Overflow用户
提问于 2017-02-14 16:32:56
回答 1查看 1.1K关注 0票数 0

我正在尝试解析下面的示例XML文件,从中获取一些数据。下面是XML文件:

代码语言:javascript
复制
<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>

从这个XML文件中,我需要获得所有的配置文件(profile1、profile2...)然后,对于每个配置文件的title标记,我需要获取其文本内容。我正在尝试实现这样的东西:

代码语言:javascript
复制
for all profile in XML{
    get its attribute "id".
    get its <title> tag's text content.
}

例如,以下是预期输出:

代码语言:javascript
复制
profile1
text1
profile2
text2  // but in my code, it is always coming text1. I am not aware of, how to place [i] 

我能拿到身份证。但不能获得其标签的文本内容。下面是我的代码:

代码语言:javascript
复制
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]);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-15 16:21:56

你可以像这样得到文本:

代码语言:javascript
复制
console.log(etree.findall('./Profile')[i].find('title').text);

但我也会对代码进行一点重构,以避免像下面这样多次调用.findall:

代码语言:javascript
复制
var profiles = etree.findall('./Profile');

for (var i = 0; i < profiles.length; i++) {
	var profile = profiles[i];

	console.log(profile.get('id'));
	console.log(profile.find('title').text);
}

希望这能有所帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42221219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档