Skip to content

Instantly share code, notes, and snippets.

@skysan87
Created July 20, 2018 17:55
Show Gist options
  • Save skysan87/9db88f63104bc17fb259ea400f2a84e8 to your computer and use it in GitHub Desktop.
Save skysan87/9db88f63104bc17fb259ea400f2a84e8 to your computer and use it in GitHub Desktop.
[JS] JavaScriptでXmlをパースする(パースにjQueryは未使用)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DomParser innerHtml Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<button id="btnTest" onclick="doAction()">実行</button>
<div id="result"></div>
<script>
function doAction() {
var xmlString = '<?xml version="1.0" encoding="UTF-8"?>'
+ '<root>'
+ '<sub1>何もにも成れないお前たち</sub1>'
+ '<sub1>'
+ '<sub_sub>sub sub text</sub_sub>'
+ '</sub1>'
+ '</root>'
;
//IE11で失敗する innerHtmlプロパティがない
// var doc = new DOMParser().parseFromString(xmlString, "text/xml");
var doc = new DOMParser().parseFromString(xmlString, "text/html");
var tags = doc.getElementsByTagName("sub_sub");
var resultString = '';
if (tags != null && tags.length > 0) {
resultString = tags[0].innerHTML;
}
console.log("result:{0}", resultString);
$("#result").text(resultString);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment