简体   繁体   中英

How to fetch Tag name using Cheerio from and XML data (JavaScript)?

I have an xml data from which I want to be able to fetch tagnames and store them or run operations based on whether a particular tag is present in data

Eg XML Data:

<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>

I am able to however fetch the values & attr as shown in below code I have been using till now:

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);

So How do I go about fetching and storing values like the tagname "Performance" under StudentValue Tag. Also I would like to do some actions based on a tagname/elements presence.

Like in JSON we can code in the below manner, in case of cheerio do we have something like this:

    if (MyData.StudentData.Student.StudentValue.hasOwnProperty('Performance'){
    //then do some actions
    console.log("Student is an Honor Student");
    }

你可以在cheerio中获得这样的标签名称

$('a').first().prop('tagName')

这就是我们如何获取子标记名

xmlData('MyData StudentData Student StudentValue').children().get(4).tagName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM