Reputation: 313
I'm trying to verify that a given string is valid svg using this little util method I made:
public static bool IsValidSvg(string str) {
try {
var svg = XDocument.Load(new StringReader(str));
return svg.Root.Name.LocalName.Equals("svg");
} catch {
return false;
}
}
This works for 90% of the cases, but, for instance, I have an svg which has an opening tag as follows:
<svg version="1.1" id="Layer_2" xmlns:x="&ns_extend;" xmlns:i="&ns_ai;" xmlns:graph="&ns_graphs;"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
x="0px" y="0px" width="599.33398px" height="490.66748px" viewBox="0 0 599.33398 490.66748"
enable-background="new 0 0 599.33398 490.66748" xml:space="preserve">
Then the validation fails because it doesn't know what ns_extend is... It throws:
System.Xml.XmlException: Referenced entity 'ns_extend' does not exist. Line 1, position 53.
How can I get around this? The svg renders properly, so it should be a valid svg...
Upvotes: 2
Views: 1977
Reputation: 3733
A quick and dirty fix for your method:
private static bool IsSvg(string input)
{
try
{
using (var file = new FileStream(input, FileMode.Open, FileAccess.Read))
using (var reader = new XmlTextReader(file) {XmlResolver = null})
return reader.Read() && reader.Name.Equals("svg", StringComparison.InvariantCultureIgnoreCase);
}
catch
{
return false;
}
}
By setting the XmlResolver
property to null
the reader will ignore DTD reference.
Upvotes: 3