用 DOMParser 讀取 XML

 

一個 XML 格式之字串如下

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
  </book>
</bookstore>

 

在前端讀取 XML 的 response 已經是字串了,之後就看你用什麼方法去解析該字串。

 

範例如下

var text, parser, xmlDoc;

text = `
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
  </book>
</bookstore>
`;

parser = new DOMParser();
xmlDoc = parser.parseFromString(text.replace('<?xml version="1.0" encoding="utf-8" >',''),"application/xml");
var title = xmlDoc.getElementsByTagName("title")[0].textContent;
console.log(title);

 

參考資料:

JavaScript 透過 DOMParser 讀取 XML

傳送與接收 XML