首页 > 解决方案 > How to access SVG parts with XPath on iOS

问题描述

I want to access values from a SVG file by using XPath on my iOS project.

I already found some libraries (Fuzi, Ono, RaptureXML, Kanna) and integrated them into my project. They all work fine for simple XML files but when I'm using a real SVG file (which is basically XML) it stops working.

For the following cutout SVG file I tried several XPath expressions.

<svg width="834px" height="707.5px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" overflow="visible">
    <defs>
        <symbol id="E003" viewBox="0 0 1000 1000" overflow="inherit">
            <path transform="scale(1,-1)" d="M0 -0c49 0 97.5 -2.26367 135.5 4.73633c206 95 258.5 264.264 263.5 271.264c0 1 -14 7 -15 6c-88 -154 -251 -167 -321 -170c-1 0 -63 -1 -63 -1v-111z" />
        </symbol>
        <symbol id="E004" viewBox="0 0 1000 1000" overflow="inherit">
            <path transform="scale(1,-1)" d="M0 0c49 0 97.5 2.26367 135.5 -4.73633c206 -95 258.5 -264.264 263.5 -271.264c0 -1 -14 -7 -15 -6c-88 154 -251 167 -321 170c-1 0 -63 1 -63 1v111z" />
        </symbol>
    </defs>
</svg>

XPath expressions: /svg //symbol //symbol[@id='E004']

I found out that the XPath expressions work if the namespace definition xmlns="http://www.w3.org/2000/svg" is removed from the SVG file.

So I registered namespaces like (Fuzi example):

document.definePrefix("", forNamespace: "http://www.w3.org/2000/svg")
document.definePrefix("svg", forNamespace: "http://www.w3.org/2000/svg")
document.definePrefix("xlink", forNamespace: "http://www.w3.org/1999/xlink")

But the expressions still don't work.

Which library, XPath expression or change is needed to get the following result for this XPath expression //symbol[@id='E004']?

Element='<symbol xmlns="http://www.w3.org/2000/svg"
        id="E004"
        overflow="inherit"
        viewBox="0 0 1000 1000">
            <path d="M0 0c49 0 97.5 2.26367 135.5 -4.73633c206 -95 258.5 -264.264 263.5 -271.264c0 -1 -14 -7 -15 -6c-88 154 -251 167 -321 170c-1 0 -63 1 -63 1v111z"
         transform="scale(1,-1)"/>
</symbol>' 

标签: xmlsvgxpath

解决方案


To access SVG element xpath has to starts-with //*[name()='svg'] or //*[local-name()='svg']

To fetch above element your xpath should be followings:

//*[name()='svg']//*[@id='E004']

OR

//*[local-name()='svg']//*[@id='E004']

OR

//*[local-name()='svg']//*[local-name()='symbol'][@id='E004']

OR

 //*[name()='svg']//*[name()='symbol'][@id='E004']

推荐阅读