我试图解析SVG文件,因为我想动态更改一些参数(尝试设置实时地图)。我正在使用Spring MVC。
这是一个简单的示例,因为我需要了解它的工作原理。
在我的控制器中
@RequestMapping(value="/")
public String getHome(ModelMap model) throws ParserConfigurationException, SAXException, IOException{
SVGParser parser = new SVGParser(loadSVG());
model.addAttribute("parser", parser);
return "home";
}
loadSVG()给我图像的xml字符串(如果在
<img>
标记中使用它,它将起作用)。private String loadSVG() throws IOException{
Resource resource = new ClassPathResource("disegno.svg");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line= br.readLine()) != null) {
stringBuilder.append(line);
}
br.close();
String svgFile = stringBuilder.toString();
return svgFile;
}
SVGParser.class是
public class SVGParser {
public SVGParser(String uri) throws ParserConfigurationException, SAXException, IOException{ //costruttore
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(uri);
String xpathExpression = "//circle/@id";
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = null;
NodeList svgPaths = null;
try {
expression = xpath.compile(xpathExpression);
svgPaths = (NodeList)expression.evaluate(document, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
svgPaths.item(0).getNodeValue();
}
}
我只想看看会发生什么来理解某些东西,但是我得到的只是:
java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Created with Inkscape (http://www.inkscape.org/) -->
这是怎么回事?
最佳答案
您应该改为使用this method。您使用的方法需要一个字符串,该字符串实际上是文档的URI。
另外,请勿“预读”内容,尤其是因为您做错了(打开阅读器而未指定编码)。只需将resource.getInputStream()
传递给上述方法即可。
并使用try-with-resources。即,像这样的东西:
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document document;
try (
final InputStream in = resource.getInputStream();
) {
document = builder.parse(in);
}
// work with document