-6ren"> -我试图解析 SVG 文件,因为我想动态更改一些参数(尝试设置实时 map )。我正在使用 Spring MVC。这是一个简单的示例,因为我需要了解它是如何工作的。 在我的 Controller 中我有-6ren">
gpt4 book ai didi

java - 解析 SVG - java.net.MalformedURLException : no protocol:

转载 作者:行者123 更新时间:2023-11-30 07:33:50 25 4
gpt4 key购买 nike

我试图解析 SVG 文件,因为我想动态更改一些参数(尝试设置实时 map )。我正在使用 Spring MVC。这是一个简单的示例,因为我需要了解它是如何工作的。

在我的 Controller 中我有

@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

关于java - 解析 SVG - java.net.MalformedURLException : no protocol: <? xml 版本 ="1.0"编码 ="UTF-8"独立 ="no"?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35686717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com