繁体   English   中英

如何自动将属性添加到特定的XML元素(R或Perl或…)

[英]How to automatically add attributes to specific XML elements (R or Perl or…)

我正在从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属性

在Perl中,使用XML :: XSH2 ,它是XML :: LibXML的包装器:

open file.svg ;
for //*[@id] set @new_attribute "newvalue" ;
save :b ;

这里是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;

在[r]中,以下内容将从kbb.com下载页面,对其进行解析以查找其href包含Fig_Vodka="Don't mind if I do" /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购买二手车(第2部分)”和“ 带有RXML和数据技术的Web技术XML和Web技术”的第6.3.1节。

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM