问题
I would like to serialize part of the DOM to XHTML (valid XML). Let's assume I have just one element inside <body>
, and that this is the element I want to serialize:
<div>
<hr>
<img src="/foo.png">
</div>
With this, document.innerHTML
gives me almost what I want, except it returns HTML, not XHTML (i.e. the <hr>
and <img>
won't be properly closed). Since innerHTML
doesn't do the trick, how can I serialize part of the DOM to XHTML?
回答1:
I am not sure if using another language (on top of the JavaScript engine) is an option. If this is of any help, this would be the XQuery (XQIB) way of doing it:
<script type="application/xquery">
serialize(b:dom()//div)
</script>
For example, in the following page, the serialized XHTML is written as text on the page instead of the script tag, after the div tag:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Serializing part of the DOM</title>
<meta charset="UTF-8"/>
<script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
</head>
<body>
<div>
<hr>
<img src="/foo.png">
</div>
<script type="application/xquery">
serialize(b:dom()//div)
</script>
</body>
</html>
The HTML DOM is mapped to the XQuery data model (a data model on top of XML). b:dom() returns the document node of the page, and //div navigates to all descendant div tags. The serialize function then serializes this to a string.
However, this will work for IE9+ (not 6+) and recent versions of Chrome, Firefox, Safari, Opera.
回答2:
this is not tested code, but I would scan recursively children of the parent element and build XHTML like this:
var parent;
var parse = function(el) {
var res = "";
for(var i=0; i < el.childNodes.length; i++) {
var child = el.childNodes[i];
res += "<"+child.tagName;
// scan through attributes
for(var k=0; k < child.attributes.length; k++) {
var attr = child.attributes[k];
res += " "+attr.name+"='"+attr.value+"'";
}
res += ">";
res += parse(child);
res += "</"+child.tagName+">";
}
return res;
}
var xhtml = parse(parent);
回答3:
Sarissa, the cross-browser Javascript compatibility library has an XMLSerializer implementation for browsers that lack one:
http://dev.abiss.gr/sarissa/jsdoc/symbols/XMLSerializer.htm
They also have an example of how to use it, which is just:
var xmlString = new XMLSerializer().serializeToString(someXmlDomNode);
According to them, the browser support for their library is good:
Supported browsers are Mozilla - Firefox and family, Internet Explorer with MSXML3.0 and up, Konqueror (KDE 3.3+ for sure), Safari and Opera.
来源:https://stackoverflow.com/questions/7576925/in-javascript-how-can-serializer-part-of-the-dom-to-xhtml