【问题标题】:How to fetch Tag name using Cheerio from and XML data (JavaScript)?如何使用 Cheerio 从 XML 数据 (JavaScript) 获取标签名称?
【发布时间】: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


【解决方案1】:

你可以像这样在cheerio中获取标签名称

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

【讨论】:

  • 嗨@pguardiario,谢谢你的回答,对不起,我是新手,我们如何检查是否存在标记名。比如检查 studentvalue 路径下是否有一个名为 Performance 的子标签,如果有,我会将 Level 标签的值存储在其中
  • 嘿,我得到了答案,谢谢:xmlData('MyData StudentData Student StudentValue').children().get(4).tagName;
【解决方案2】:

这就是我们获取子标记名的方式

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多