Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse embedded XML with JavaScript

I’m failing to parse a XML document embedded in a script tag with Vanilla JavaScript:

document.addEventListener('DOMContentLoaded', function() {
  const xmlStr = document.getElementById('xml').innerText;
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlStr,'text/xml');
  const barText = xmlDoc.getElementById('bar').textContent;
  alert(barText)
});
<body>

  <h1>Parsing &lt;script type="text/xml"&gt with JavaScript</h1>

  <script id="xml" type="text/xml">
<?xml version="1.0" encoding="utf-8"?>
<foo>
  <bar id="bar">Hello world!</bar>
</foo>
  </script>

</body>

What’s the problem here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As explained by the error message,

const xmlStr = document.getElementById('xml').textContent;
const xmlDoc = new DOMParser().parseFromString(xmlStr, 'text/xml');
console.log(new XMLSerializer().serializeToString(xmlDoc));
<script id="xml" type="text/xml">
<?xml version="1.0" encoding="utf-8"?>
<foo>
  <bar id="bar">Hello world!</bar>
</foo>
</script>

XML Parsing Error: XML or text declaration not at start of entity

You can’t have whitespace, newlines included, before <?xml …?>.

const xmlStr = document.getElementById('xml').textContent;
const xmlDoc = new DOMParser().parseFromString(xmlStr, 'text/xml');
console.log(xmlDoc.getElementById('bar').textContent);
<script id="xml" type="text/xml"><?xml version="1.0" encoding="utf-8"?>
<foo>
  <bar id="bar">Hello world!</bar>
</foo>
</script>

(see also trimStart)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading