【发布时间】:2019-06-04 13:25:19
【问题描述】:
我有一个 xml 数据,我希望能够从中获取标记名并存储它们或根据数据中是否存在特定标记来运行操作
例如 XML 数据:
<MyData version="3.0">
<StudentData type="Table">
<Student type="Table">
<StudentValue type="Table">
<DateOfBirth type="Data">2009-05-31</DateOfBirth>
<StudenClass type="Data">Sixth</StudenClass>
<StudentRoll type="Data">006</StudentRoll>
<Name type="Table">
<FirstName type="Data">MMMMM</FirstName>
<LastName type="Data">XXXXXXX</LastName>
</Name>
<Performance type="Table">
<Level type="Data">Honor</Level>
</Performance>
</StudentValue>
<Contact type="Table">
<Email type="Data">xyx@xyz.com</Email>
</Contact>
</Student>
</StudentData>
我可以获取值和属性,如下面的代码所示:
xml= '<MyData version="3.0"><StudentData type="Table"><Student type="Table"><StudentValue type="Table"><DateOfBirth type="Data">2009-05-31</DateOfBirth><StudenClass type="Data">Sixth</StudenClass><StudentRoll type="Data">006</StudentRoll><Name type="Table"><FirstName type="Data">MMMMM</FirstName><LastName type="Data">XXXXXXX</LastName></Name><Performance type="Table"><Level type="Data">Honor</Level></Performance></StudentValue><Contact type="Table"><Email type="Data">xyx@xyz.com</Email></Contact></Student></StudentData></MyData>';
var xmlData = cheerio.load(xml, {
ignoreWhitespace: true,
xmlMode: true
});
var studentName = xmlData('MyData StudentData Student StudentValue Name').eq(0).text();
var attr = xmlData('MyData StudentData Student StudentValue Name').eq(0).attr();
var find = xmlData('MyData StudentData Student StudentValue Name').get(0).tagname;
console.log(studentName);
console.log(attr);
console.log(find);
那么,我该如何获取和存储诸如 StudentValue 标签下的标签名“Performance”之类的值。 另外我想根据标记名/元素的存在做一些动作。
像在 JSON 中一样,我们可以用以下方式编码,如果是 Cheerio,我们是否有这样的东西:
if (MyData.StudentData.Student.StudentValue.hasOwnProperty('Performance'){
//then do some actions
console.log("Student is an Honor Student");
}
【问题讨论】:
-
不清楚你在找什么。
-
@pguardiario:我希望能够存储诸如 Performance 之类的标记名,如上面的 xml 数据中所示。我做不到。
-
我能够获取诸如荣誉等值,但不能获取标签名称本身
标签: javascript xml cheerio