batik配合XPath解析svg文件


<!-- SVG解析包 -->
<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>batik-all</artifactId>
    <version>1.12</version>
    <type>pom</type>
</dependency>
<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>
//You first load the XML as a Document:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("image.svg");
//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";
//Now we can instantiate the XPath processor and compile the expression:
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expression = xpath.compile(xpathExpression);
//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();

文章作者: wuzhiyong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 wuzhiyong !
评论
 上一篇
dom4j获取xml所有节点 dom4j获取xml所有节点
public class Dom4jTest { public static void main(String[] args) throws DocumentException { String svgURI =
2020-04-21
下一篇 
Xpath元素定位 Xpath元素定位
Xpath简介XPath是XML Path的简称,它是一种用来确定XML(可扩展标记语言)文档中某部分位置的语言。Xpath也是一种表达式语言,它基于XML的树状结构,可以用来在整个树中来寻找指定的节点,因此它的返回值可能是节点,节点集合,
2020-04-21
  目录