我读了这个xml并尝试获取不同的节点值。我可以只查找特定节点并获取值,但问题是有多个节点具有相同的名称。所以,当我得到它的值时,它给了我指定的所有节点值。我想分别获取每个节点的值。任何帮助将不胜感激。提前谢谢。
这是xml:
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register1</Operation>
</LogLine>
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register2</Operation>
</LogLine>
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register3</Operation>
</LogLine>
我做了什么
success: function(xml) {
var xmlDoc = jQuery.parseXML(xml);
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$dateTime = $xml.find( "DateTime" );
$( "#xmlElement" ).append( "Log In Information: "+$dateTime .text() );
}
HTML:
当前输出: 2016-11-17T18:31 + 00002016-11-17T18:31 + 00002016-11-17T18:31 + 0000
答案 0 :(得分:2)
这似乎有效,
您的XML最初无效,我添加了LINES,部分..
var xml = `<Lines>
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register1</Operation>
</LogLine>
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register2</Operation>
</LogLine>
<LogLine>
<DateTime>2016-11-17T16:48+0000</DateTime>
<Operation>Register3</Operation>
</LogLine></Lines>`;
$(function () {
var xmlDoc = $($.parseXML( xml ));
xmlDoc.find('Lines LogLine').each(function () {
var $t = $(this);
console.log(
$t.find('DateTime').text() + ' ' +
$t.find('Operation').text()
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:1)
试试这个,
success: function(xml) {
var resultXML = $.parseXML(xml);
//loop over each 'LogLine' element node
$(resultXML).find('LogLine').each(function(index){
//within each 'LogLine' node find 'DateTime' node
var dateTime = $(this).find( "DateTime" );
$( "#xmlElement" ).append( "Log In Information: "+dateTime.text() );
}
}