最近、Jquery を使用して JavaScript で小さな 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());
}
返される子の数が 2 であるべきなのに、なぜ 3 なのかわかりません。Jquery のドキュメントに記載されているように、children 関数は XML ツリーの最初のレベルのみをチェックする必要があります。
テストとして使用される XML は次のとおりです。
<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>
ご覧のとおり、質問の子の数は 2 です。
私が得た結果は次のとおりです。
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
手伝って頂けますか?