9716278
9716278

Reputation: 2404

How to get element from svg using xpath python lxml, but returning empty list?

I'm trying to edit an SVG file with python-3 and lxml. So far, I'm stuck on getting an element form the SVG with xpath.

from lxml import etree

boarder = etree.parse('boarder.svg')

Bd = boarder.xpath('//g/path')

print(Bd)

When I run the code, I get back:

[]

Which is an empty list. I'm tring to access the g/path element as an element so that I can change its attributes.

This is the SVG I'm working with ('boarder.svg'):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   id="svg8"
   version="1.1"
   viewBox="0 0 10 10"
   height="10mm"
   width="10mm">
  <defs
     id="defs2" />
  <metadata
     id="metadata5">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     transform="translate(0,-287)"
     id="layer1">
    <path
       id="rect1379"
       d="m 1.1663527,287.97964 h 7.6672946 v 7.6673 H 1.1663527 Z"
       style="opacity:0.95;fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.89999998;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" />
  </g>
</svg>

So far I've already tryed:

Upvotes: 0

Views: 2139

Answers (2)

Sweet Sheep
Sweet Sheep

Reputation: 336

Similar to mzjn's comment on OP, I sussed out a way to do this a bit more generically/nicely:

boarder = etree.parse('boarder.svg')
ns = boarder.getroot().nsmap
Bd = boarder.xpath('//g/path', ns)
print(Bd)

This also works with find, findall, and iterfind.

Upvotes: 0

KunduK
KunduK

Reputation: 33384

To find svg element try following xpath.Use local-name() or name()

from lxml import etree,html

boarder = etree.parse('boarder.svg')
Bd = boarder.xpath('//*[local-name()="svg"]//*[local-name()="g"]/*[local-name()="path"]/@id')[0]
print(Bd)
Bd = boarder.xpath('//*[local-name()="svg"]//*[local-name()="g"]/*[local-name()="path"]/@d')[0]
print(Bd)

OR

Bd = boarder.xpath('//*[name()="svg"]//*[name()="g"]/*[name()="path"]/@id')[0]
print(Bd)
Bd = boarder.xpath('//*[name()="svg"]//*[name()="g"]/*[name()="path"]/@d')[0]
print(Bd)

Output:

rect1379
m 1.1663527,287.97964 h 7.6672946 v 7.6673 H 1.1663527 Z

Upvotes: 3

Related Questions