【发布时间】:2021-11-30 13:48:17
【问题描述】:
我尝试向 XML (svg) 文档添加一个新节点,但是当我随后尝试使用 XPath 表达式查询它时,它找不到新节点。
use strict;
use warnings;
use XML::LibXML;
use XML::LibXML::XPathContext;
my $parser = XML::LibXML->new();
my $svg = $parser->load_xml(string => <<'SVG');
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
<g inkscape:groupmode="layer" id="old-id" inkscape:label="old-label">...</g>
</svg>
SVG
my $layer = XML::LibXML::Element->new('g'); # same result with 'svg:g'
$layer->setAttribute('inkscape:groupmode', 'layer');
$layer->setAttribute('id', 'new-id');
$layer->setAttribute('inkscape:label', 'new-label');
$svg->documentElement()->appendChild($layer);
print "Dump:\n$svg\n";
print "Xpath:\n";
my $xpc = XML::LibXML::XPathContext->new($svg);
$xpc->registerNs('svg', 'http://www.w3.org/2000/svg');
my $xpath = '//svg:g';
foreach my $node ($xpc->findnodes($xpath)) {
print $node->getAttribute('id'), ": ", $node->getAttribute('inkscape:label'), "\n";
}
打印出来:
Dump:
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
<g inkscape:groupmode="layer" id="old-id" inkscape:label="old-label">initially</g>
<g inkscape:groupmode="layer" inkscape:label="new-label" id="new-id"/></svg>
Xpath:
old-id: old-label
当我转储整个 xml 文档时会显示新节点,但 XPath 表达式只报告旧节点。
为什么会这样?如何让 XPath 表达式也找到新添加的节点?
【问题讨论】:
-
也许你需要像这样创建元素:
$root = $dom->documentElement(); $dom->setDocumentElement( $root ); $element = $dom->createElement( $nodename );,然后追加。该元素是在文档中创建的,但尚未分配到任何地方。来自here