XML之在script中載入一段XML字串
阿新 • • 發佈:2019-01-26
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>逆水行舟不進則退</title> </head> <body> <script> text = "<bookstore><book>"; text = text + "<title>Everyday</title>"; text = text + "<author>li</author>"; text = text + "<year>2018</year>"; text = text + "</book></bookstore>"; parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); document.write("XML 字串載入到 XML DOM 物件"); console.log(xmlDoc); // 將text列印到控制檯 </script> </body> </html>
最好把上面的內容呼叫方式封裝在一個檔案當中以便使用,定義一個檔案loadxmlstring.js
function loadXMLString(txt)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
return xmlDoc;
}
然後再script的src進行載入
<html> <head> <script src="loadxmlstring.js"></script> </head> <body> <script> text="<bookstore>" text=text+"<book>"; text=text+"<title>Everyday Italian</title>"; text=text+"<author>Giada De Laurentiis</author>"; text=text+"<year>2005</year>"; text=text+"</book>"; text=text+"</bookstore>"; xmlDoc=loadXMLString(text); </script> </body> </html>