我正在从inkscape生成SVg文件,并希望自动编辑它们,以便向文件中的选定元素添加一些属性。
假设原来的SVG是这样的
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" fill="red" id="red-circle"/>
<circle cx="100" cy="50" r="40" fill="green" />
</svg> 然后,我希望找到具有和id的元素,并向这些元素中添加一些其他属性,如最后的xml如下所示
<svg height="100" width="100">
<circle cx="50" cy="50" r="40" fill="red" id="red-circle" new-attribute="newvalue"/>
<circle cx="100" cy="50" r="40" fill="green" />
</svg> 我想知道最好的方法是自动化这个过程(使用标记id查找元素并向它们添加新的属性)。我需要对大量的SVG文件进行处理,所以自动化是绝对必要的.我想在R或Perl中这样做,但我愿意接受任何建议。
PS: SVG的总体结构可能会在文档之间发生变化,所以我不能依靠文档的结构来解析它。我唯一的线索是某些元素有一个id属性
发布于 2014-03-10 15:06:44
这里是一个XML::Twig版本,尽管我发现choroba的答案非常令人高兴:
#!/usr/bin/perl
use strict;
use warnings;
use XML::Twig;
# configuration
my ($infile, $id) = ('diag.svg', 'red-circle');
my ($att, $value) = ('attribute', 'value');
# processing
my $twig = XML::Twig->new(
    keep_spaces => 1,
    twig_handlers => {
        qq([\@id = "$id"]) => sub {
            $_->set_att($att, $value);
        },
    },
);
$twig->parsefile($infile);
# output
$twig->print;发布于 2014-03-10 14:21:56
在Perl中,使用XML::XSH2 ( XML::LibXML的包装器)
open file.svg ;
for //*[@id] set @new_attribute "newvalue" ;
save :b ;发布于 2015-04-03 18:06:40
在r中,下面将从kbb.com下载一个页面,解析它以查找锚标记,其中包含href的/honda/accord/,然后将属性Fig_Vodka="Don't mind if I do"添加到所述已解析标记的XMLNodeSet中。
library(XML)
## download the webpage
kbbHTML <- readLines("http://www.kbb.com/used-cars/honda/accord/2014/private-party-value")
## parse the downloaded document to an XMLInternalDocument
kbbInternalTree <- htmlTreeParse(kbbHTML,useInternalNodes=T)
#kbbInternalTree <- htmlParse(kbbHTML, asText = TRUE) #equally valid parsed content as above
## select nodes matching our XPath expression
specific.nodes <- getNodeSet(doc = kbbInternalTree, path ="//a[contains(@href,'/honda/accord/')]")
sapply(specific.nodes, function(x) xmlAttrs(x)<-c(Fig_Vodka="Don't mind if I do"))以上代码取自如何用R购买二手车(第二部分)和基于R的数据科学的XML和Web技术第6.3.1节。
干杯!
https://stackoverflow.com/questions/22301962
复制相似问题