2016-02-28 24 views
1

我試圖解析的SVG文件,因爲我想動態更改某些參數(嘗試設置實時地圖)。我正在使用Spring MVC。 這是一個簡單的例子,因爲我需要了解它是如何工作的。解析SVG - java.net.MalformedURLException:沒有協議:<?XML版本= 「1.0」 編碼= 「UTF-8」 獨立= 「否」?>

在我的控制器我有

@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/) --> 

這是怎麼回事?

回答

1

您應該使用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 
+0

感謝,異常已經走了,現在我有SVGParser的一個實例,接下來的工作就是要了解如何從中得到物品 – besmart

相關問題