为了简单地提取path
您可以使用 XPath 获取数据。
假设你有这个 SVG 并且你想提取所有path
数据(来自双方path
元素):
<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 作为文档加载:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("image.svg");
然后使用 XPath 选择所需的节点。下面的表达式选择的内容d
所有的属性path
文件内的元素:
String xpathExpression = "//path/@d";
现在我们可以实例化 XPath 处理器并编译表达式:
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = xpath.compile(xpathExpression);
由于预期结果是一个节点集(两个字符串),我们使用以下方法计算 SVG 文档上的表达式XPathConstants.NODESET
作为第二个参数:
NodeList svgPaths = (NodeList)expression.evaluate(document, XPathConstants.NODESET);
从那里您可以使用以下命令提取第一组路径数据:
svgPaths.item(0).getNodeValue();