This question already has an answer here:
I'm a beginner in web development, and I'm trying to insert line breaks in my XML file. This is what my XML looks like:
<musicpage>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
<song>
<title>Song Title</title>
<lyric>Lyrics</lyric>
</song>
</musicpage>
I want to have line breaks in between the sentences for the lyrics. I tried everything from /n, and other codes similar to it, PHP parsing, etc., and nothing works! Have been googling online for hours and can't seem to find the answer. I'm using the XML to insert data to an HTML page using Javascript.
Does anyone know how to solve this problem?
And this is the JS code I used to insert the XML data to the HTML page:
<script type="text/javascript">
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","xml/musicpage_lyrics.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
var x=xmlDoc.getElementsByTagName("songs");
for (i=0;i<x.length;i++) {
document.write("<p class='msg_head'>");
document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
document.write("</p><p class='msg_body'>");
document.write(x[i].getElementsByTagName("lyric")[0].childNodes[0].nodeValue);
document.write("</p>");
}
</script>
(Sung to the tune of Home on the Range)
If it was mine I'd wrap the choruses and verses in XML elements as well.
In XML a line break is a normal character. You can do this:
and the contents of
<text>
will beIf this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like
\n
won't work, on the other hand, because XML has no escape sequences*.* Note that


is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.This is where neither


nor things like\n
will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use
<br>
tags to force line breaks on screen.Here is a JavaScript function that inserts
<br>
into a multi-line string:Alternatively you can force line breaks at new line characters with CSS: