使用Java读取svg路径数据的最简单方法?

时间:2014-02-23 20:03:43

标签: java xpath svg batik

我正在寻找使用svg图像并解析/处理不同的路径来进行自定义转换。在Java中,简单地提取路径数据的最简单方法是什么?我正在查看apache xmlgraphics / batik包,但是如何返回路径类型和参数并不是很明显。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

要简单地提取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);

由于预期结果是一个节点集(两个字符串),我们使用XPathConstants.NODESET作为第二个参数来评估SVG文档中的表达式:

NodeList svgPaths = (NodeList)expression.evaluate(document, XPathConstants.NODESET);

从那里你可以使用以下方法提取第一组路径数据:

svgPaths.item(0).getNodeValue();
相关问题