[英]Using Javascript To Parse XML and Create Objects From The Retrieved Values
I am trying to parse an XML document but i am a little bit confused just how i go about it. 我试图解析一个XML文档,但我有点困惑,我是如何去做的。 For example below shows my XML document
例如,下面显示了我的XML文档
<document>
<object name="Customer" type="class" x="137" y="63">
<attributes>
</attributes>
<methods>
</methods>
</object>
<object name="Item" type="class" x="539" y="275">
<attributes>
</attributes>
<methods>
</methods>
</object>
<link start="Customer" end="Item" type="generalization" />
</document>
In my case i need to loop through each "object" and create an object, in my app, this is simple enough: objectArray.push(new uml_Class(name));
在我的情况下,我需要遍历每个“对象”并创建一个对象,在我的应用程序中,这很简单:
objectArray.push(new uml_Class(name));
. 。
Now how would i loop through each <object>
on the document and then insert its name value into an array? 现在,我将如何遍历文档上的每个
<object>
,然后将其名称值插入到数组中?
I've read that the function getElementsByTagName()
is to be used but this does not work for me: 我已经读过要使用函数
getElementsByTagName()
但这对我不起作用:
alert(documentXML);
var root = documentXML.getElementsByTagName('Object');
It does alert my XML in the documentXML
variable but then firebug tells me the following: documentXML.getElementsByTagName is not a function
它确实在
documentXML
变量中提醒我的XML,但是firebug告诉我以下内容: documentXML.getElementsByTagName is not a function
How would i loop through an XML document, repeatedly making objects? 我如何循环遍历XML文档,重复制作对象?
You may be interested in jQuery's built in XML parsing capabilities . 您可能对jQuery内置的XML解析功能感兴趣。
Example (borrowed from link): 示例(从链接借来):
$(document).ready(function () {
$.ajax({
type: "GET",
url: "books.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$('#load').fadeOut();
$(xml).find("Book").each(function () {
$(".main").append('<div class="book"><div class="title">' + $(this).find("Title").text() + '</div><div class="description">' + $(this).find("Description").text() + '</div><div class="date">Published ' + $(this).find("Date").text() + '</div></div>');
$(".book").fadeIn(1000);
});
}
As it is a XML document, tag names are not case invariant. 由于它是XML文档,因此标记名称不是大小写不变的。
var objects = documentXML.getElementsByTagName('object');
should work. 应该管用。
document.getElementsByTagName()
is available on all Document object, I fear you missed to parse the string with a DOMParser
. document.getElementsByTagName()
在所有Document对象上都可用,我担心你错过了使用DOMParser
解析字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.