var circ = defs.append("svg:g").attr("id", "centerCircle")
Now how do I append an XML string to it? (In real life,
of course, the string would contain hundreds of paths)
var str = '<circle cx="75" cy="50" r="25"/>'
circ.text(str) // appends escaped text, no elements
circ.html(str) // doesn't append anything
circ.xml(str) // call doesn't exist. :)
circ.innerHTML = str // doesn't append anything
circ.appendChild(str) // doesn't append anything, getting desperate
...
Do I need to use jQuery to parse it and convert it? Or
write my own parser?
Full script below. Thanks for pointing out if I'm missing
something obvious!
- Scott
<!doctype html>
<html>
<head>
<title>test</title>
<script type="text/javascript"
src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<script type="text/javascript">
var svg = d3.select('body').append('svg:svg')
.attr("width", 512).attr("height", 342)
var defs = svg.append("svg:defs")
var circ = defs.append("svg:g").attr("id", "centerCircle")
circ.appendChild('<circle cx="75" cy="50" r="25"/>') // doesn't work
svg.append("svg:use").attr("xlink:href", "#centerCircle")
.attr("x", 75).attr("y", 25).attr("id", "comp1")
</script>
</body>
</html>
The short answer is that you can't.
You can append HTML strings using the HTML operator, but as far as I
know there's no way to insert XML strings. For one thing, there's the
whole namespace problem—your circle element doesn't have a namespace,
but somehow the browser would need to know you mean an SVG circle
element.
Why do you want to do this?
If you want to create a circle element, use D3's append or insert
operator for creating elements:
defs.append("svg:g")
.attr("id", "centerCircle")
.append("svg:circle")
.attr("cx", 75)
.attr("cy", 70)
.attr("r", 25);
If you have an existing SVG file that you want to embed in the page,
you can either include it as a static image, or you can load it using
d3.xml(file, callback). You can then using element.appendChild to
insert the loaded SVG file into the current document.
Mike
I read your response and took a crack at loading and appending but I'm
getting an error. The file I'm trying to use is this:
http://upload.wikimedia.org/wikipedia/commons/0/03/BlankMap-World6.svg
I want to load the svg so I can edit the colours of different
countries using D3
When you say to use the d3.xml(file, callback) is this along the lines
of what you mean?
d3.xml("BlankMap-World6.svg", function(mapdata){
var elem = document.getElementById("map");
elem.appendChild(mapdata);
});
I wasn't creating the node. In the gist link, the following works:
d3.xml("rect01.svg", "image/svg+xml", function(xml) {
var importedNode = document.importNode(xml.documentElement, true);
document.body.appendChild(importedNode);
});