Read lines of an xml doesn't show the tags
I'm reading an开发者_运维技巧 xml file line by line:
var lines = $(xml).text().split("\n");
$.each(lines, function(n, elem) {
console.log(elem);
});
As a result, this only outputs the content between the tags, not the xml lines themselves. I've been looking for what could "trim" the lines from the enclosing tags, but haven't been successful at it.
When you do $(xml)
, you construct a node tree from the string xml
. Then, with text()
, you treat this node tree as HTML and obtain the text contents of each tag.
e.g.
var myHTML = '<b>Hi world!</b>';
console.log(myHTML); // <b>Hi world!</b>
console.log($(myHTML)); // [ b ]
console.log($(myHTML).html()); // <b>Hi world!</b>
console.log($(myHTML).text()); // Hi world!
(There are more examples of this on the jQuery .text()
documentation page; you should read the documentation for every function you use.)
But there's no need here for you to be constructing a node tree only to attempt to re-obtain the source XML after-the-fact. In fact, .html()
does not work on XHTML or XML.
Instead, just use xml
like you would any other string:
var lines = xml.split("\n");
$.each(lines, function(n, elem) {
console.log(elem);
});
精彩评论