Jquery不正确的孩子数XML解析器
最近我遇到了使用Jquery在JavaScript中编写小型XML解析器的问题。这我使用完成这项任务的代码如下:Jquery不正确的孩子数XML解析器
/*Private */
var XMLObject=$.parseXML(dataXml);
var $XMLObject=$(XMLObject);
var questionNumber=0;
// array of XML objects
var questionsXML= new Array();
/** Html questions */
//array of strings
var questionsHTML= new Array();
/*********************
* Constructor *
*********************/
a=$XMLObject.find("questions");
a.children().each(function() {
console.log("XML : " + new XMLSerializer().serializeToString(this));
questionsXML[questionNumber]=this;
questionNumber++;
});
this.getXML=function() {
var out = new XMLSerializer().serializeToString(this.XMLObject);
return out;
}
this.getQuestionNumber=function() {
return questionNumber;
}
// This function returns the question sequentially.
this.getQuestion=function() {
}
Test function :
function testXML() {
var xml ="XML see later"
var Obj= new XMLQuestions(xml);
console.log("Question Number: " + Obj.getQuestionNumber());
}
我不明白,为什么返回的儿童人数为3时,它应该是2,因为它是在jQuery的文档孩子说功能应该只检查XML树的第一级。
用作测试的XML是follwing一个:
<questionnaire>
<questions>
<question id="1">
<number></number>
<title>Q1</title>
<answers >
<answer type="TextInput">
<result>ss</result>
<questions>
<title>Hidden</title>
</questions>
</answer>
</answers>
</question>
<question id="2">
<title>Q2</title>
</question>
</questions>
</questionnaire>
,你可以看到问题的儿童的数量是两个。
结果我有这么票价为:
XML : <question id="1"> <number/> <title>Q1</title> <answers> <answer type="TextInput"> <result>ss</result> <questions> <title>Hidden</title> </questions> </answer> </answers> </question> question.js:24
XML : <question id="2"> <title>Q2</title> </question> question.js:24
XML : <title>Hidden</title> question.js:24
Question Number: 3
你能帮助我吗?
不叫this.XMLObject
在没有这种属性的情况下会导致错误?你正在定义var XMLObject
,它与this.XMLObject
不一样;
也调用this.$XMLObject
当实际变量不是属性应该也会引发异常。
另一件事:尝试使用questionsXML.push(this)
而不必增加变量questionNumber
。并返回计数使用return questionsXML.length
。
除此之外,我认为你的代码应该返回正确的值。或者也许还有更多children
(内部节点/值)。
XML测试:
<questionnaire>
<questions>
<question id="1">
<number></number>
<title>Q1</title>
<answers>
<answer type="TextInput">
<result>ss</result>
</answers>
</question>
<question id="2">
<number></number>
<title>Q1</title>
<answers>
<answer type="TextInput">
<result>sSSs</result>
</answers>
</question>
</questions>
</questionnaire>
我把错误的代码....我会更新 – 2013-02-21 15:33:12
正确的数字不是3,而是2 – 2013-02-21 15:33:35
如果这是你使用的实际XML,它应该根本不工作...标记是有点搞砸向上。你可以试试我的结果吗? – Martin 2013-02-21 15:43:20
你正在写自己的解析器,任何具体的原因是什么?有这么多解析器已经可用。 – 2018-01-23 04:27:45