<
html
>
< body >
< script type ="text/javascript" >
var text = " <note> " ;
text = text + " <to>Tove</to> " ;
text = text + " <from>Jani</from> " ;
text = text + " <heading>Reminder</heading> " ;
text = text + " <body>Don't forget me this weekend!</body> " ;
text = text + " </note> " ;
// code for IE
if (window.ActiveXObject)
{
var doc = new ActiveXObject( " Microsoft.XMLDOM " );
doc.async = " false " ;
doc.loadXML(text);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser = new DOMParser();
var doc = parser.parseFromString(text, " text/xml " );
}
var x = doc.documentElement;
document.write( " Text of first child element: " );
document.write(x.childNodes[ 0 ].childNodes[ 0 ].nodeValue);
document.write( " <br /> " );
document.write( " Text of second child element: " );
document.write(x.childNodes[ 1 ].childNodes[ 0 ].nodeValue);
</ script >
</ body >
</ html >
< body >
< script type ="text/javascript" >
var text = " <note> " ;
text = text + " <to>Tove</to> " ;
text = text + " <from>Jani</from> " ;
text = text + " <heading>Reminder</heading> " ;
text = text + " <body>Don't forget me this weekend!</body> " ;
text = text + " </note> " ;
// code for IE
if (window.ActiveXObject)
{
var doc = new ActiveXObject( " Microsoft.XMLDOM " );
doc.async = " false " ;
doc.loadXML(text);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser = new DOMParser();
var doc = parser.parseFromString(text, " text/xml " );
}
var x = doc.documentElement;
document.write( " Text of first child element: " );
document.write(x.childNodes[ 0 ].childNodes[ 0 ].nodeValue);
document.write( " <br /> " );
document.write( " Text of second child element: " );
document.write(x.childNodes[ 1 ].childNodes[ 0 ].nodeValue);
</ script >
</ body >
</ html >
返回结果:
Text of first child element: Tove
Text of second child element: Jani