I have an XML file in a string variable ($data
), and a hash containing all the tag names and their contents (%field_list
).
我有一个字符串变量($ data)中的XML文件,以及一个包含所有标记名称及其内容(%field_list)的哈希。
The tag names are to be checked so that if they are enumerated fields, their contents should be replaced with strings.
要检查标记名称,以便如果它们是枚举字段,则应将其内容替换为字符串。
Does anybody know if it is possible to do this with search and replace? I am not having much luck at the moment.
有人知道是否可以通过搜索和替换来做到这一点?我此刻没有太多运气。
foreach my $field (sort keys %field_list)
{
my $value = $field_list{$field};
# will return a non-empty string if field is enumerated and value is valid
my $enum_string = &convert_enumeration_to_string($field, $value);
if ($enum_string ne "")
{
#syntax error
$data =~ s/<($field)>($value)</($field)>/<($field)>($enum_string)</($field)>/g;
}
}
Does anybody know whether there is anything I can do, or do I need a completely different approach?
有人知道我能做什么,或者我需要一种完全不同的方法吗?
3 个解决方案
#1
3
Escape your slashes:
逃避你的斜线:
$data =~ s/<($field)>($value)<\/($field)>/<($field)>($enum_string)<\/($field)>/g;
Or use different deliminators:
或者使用不同的分隔符:
$data =~ s{<($field)>($value)</($field)>}{<($field)>($enum_string)</($field)>}g;
#2
1
Well, let's jump into the XML bandwagon: use an XML library like XML::LibXML to manipulate XML documents.
好吧,让我们跳进XML的潮流:使用像XML :: LibXML这样的XML库来操作XML文档。
use XML::LibXML;
my $dom = XML::LibXML->load_xml(string => $data);
foreach my $field (sort keys %field_list) {
my $value = $field_list{$field};
if (my $enum_string = &convert_enumeration_to_string($field, $value)) {
foreach my $node ($dom->findnodes("//xml/${field}[. = '$value']")
->get_nodelist) {
my $element = $dom->createElement($field);
$element->appendText($enum_string);
$node->replaceNode($element);
}
}
}
print $dom->toString;
#3
0
The correct way to do it is:
正确的方法是:
$data =~ s/<($field)>($value)<\/($field)>/<$field>$enum_string<\/$field>/g;
#1
3
Escape your slashes:
逃避你的斜线:
$data =~ s/<($field)>($value)<\/($field)>/<($field)>($enum_string)<\/($field)>/g;
Or use different deliminators:
或者使用不同的分隔符:
$data =~ s{<($field)>($value)</($field)>}{<($field)>($enum_string)</($field)>}g;
#2
1
Well, let's jump into the XML bandwagon: use an XML library like XML::LibXML to manipulate XML documents.
好吧,让我们跳进XML的潮流:使用像XML :: LibXML这样的XML库来操作XML文档。
use XML::LibXML;
my $dom = XML::LibXML->load_xml(string => $data);
foreach my $field (sort keys %field_list) {
my $value = $field_list{$field};
if (my $enum_string = &convert_enumeration_to_string($field, $value)) {
foreach my $node ($dom->findnodes("//xml/${field}[. = '$value']")
->get_nodelist) {
my $element = $dom->createElement($field);
$element->appendText($enum_string);
$node->replaceNode($element);
}
}
}
print $dom->toString;
#3
0
The correct way to do it is:
正确的方法是:
$data =~ s/<($field)>($value)<\/($field)>/<$field>$enum_string<\/$field>/g;