我想转换一段XML文本为对象,应该怎么办?
<SCRIPT LANGUAGE= "JavaScript ">
function getXML() {
var XML = " <human> "
XML = XML+ " <man> 男人 </man> <woman> 女人 </woman> ";
XML = XML+ " </human> ";
return XML;
}
function execute() {
var person = getXML();
//var human = person.getElementsByTagName( "human ");
alert(typeof(person));
}
</SCRIPT>
<input type=button value=tttt onclick= "execute() ">
我现在用getXML得到了XML文本,我想对其进行解析,但是好像不行,用不了getElementsByTagName这个方法,因为person的类型是string,那么我应该怎么解析这段XML呢?
------解决方案-------------------- <SCRIPT LANGUAGE= "JavaScript ">
function getXML() {
var XML = " <human> "
XML = XML+ " <man> 男人 </man> <woman> 女人 </woman> ";
XML = XML+ " </human> ";
return XML;
}
function execute() {
var doc = new ActiveXObject( "MSXML2.DOMDocument ");
doc.async =false;
doc.loadXML(getXML());
var person = doc.selectSingleNode( "//man ");
alert(person.text)
person = doc.documentElement.getElementsByTagName( "man ");
alert(person[0].text)
}
</SCRIPT>
<input type=button value=tttt onclick= "execute() ">
------解决方案--------------------function loadXML(st){
var result = null;
if(Browser.isIE){
result = getXMLDOM();
if(result) result.loadXML(st);
}else{
var parser = new DOMParser();
result = parser.parseFromString(st, "text/xml ");
}
return result;
}