用Java读取svg路径数据的最简单方法?
我希望使用svg图像并解析/处理不同的路径以进行自定义转换.在Java中,最简单的方法是简单地提取路径数据?我正在查看apache xmlgraphics/batik包,但是如何返回路径类型和参数并不是很明显.有什么建议吗?
I'm looking to consume an svg image and parse/process the different paths to do a custom conversion. What is the easiest way, in Java, to simply extract the path data? I was looking at the apache xmlgraphics/batik packages, but it's not real obvious how to return the path types and parameters. Any suggestions?
要简单地提取path
数据,可以使用XPath.
To simply extract the path
data you can use XPath.
假设您有此SVG,并且要提取所有path
数据(从两个path
元素中提取):
Suppose you have this SVG and you want to extract all the path
data (from both path
elements):
<svg>
<rect x="1" y="1" width="1198" height="598"
fill="none" stroke="blue" stroke-width="1" />
<path d="M200,300 Q400,50 600,300 T1000,300"
fill="none" stroke="red" stroke-width="5" />
<g fill="black" >
<circle cx="200" cy="300" r="10"/>
<circle cx="600" cy="300" r="10"/>
<circle cx="1000" cy="300" r="10"/>
</g>
<g fill="#888888" >
<circle cx="400" cy="50" r="10"/>
<circle cx="800" cy="550" r="10"/>
</g>
<path d="M200,300 L400,50 L600,300 L800,550 L1000,300"
fill="none" stroke="#888888" stroke-width="2" />
</svg>
您首先将XML加载为文档:
You first load the XML as a Document:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("image.svg");
然后使用XPath选择所需的节点.下面的表达式选择文件中所有path
元素的d
属性的内容:
Then you use XPath to select the desired nodes. The expression below selects the contents of the d
attributes of all the path
elements inside the file:
String xpathExpression = "//path/@d";
现在,我们可以实例化XPath处理器并编译表达式:
Now we can instantiate the XPath processor and compile the expression:
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = xpath.compile(xpathExpression);
由于预期结果是一个节点集(两个字符串),因此我们使用XPathConstants.NODESET
作为第二个参数来评估SVG文档上的表达式:
Since the expected result is a node-set (two strings), we evaluate the expression on the SVG document using XPathConstants.NODESET
as the second parameter:
NodeList svgPaths = (NodeList)expression.evaluate(document, XPathConstants.NODESET);
您可以从此处使用以下命令提取第一组路径数据:
From there you can extract the first set of path data using:
svgPaths.item(0).getNodeValue();