gpt4 book ai didi

xml - 如何打印出属性值而不是元素内容?

转载 作者:数据小太阳 更新时间:2023-10-29 02:28:15 27 4
gpt4 key购买 nike

我有一个这样的 XML 文件:

     <wave waveID="1">
<well wellID="1" wellName="A1">
<oneDataSet>
<rawData>0.1123975676</rawData>
</oneDataSet>
<well>

我正在尝试使用以下代码打印出 wellName 属性:

my @n1 = $xc->findnodes('//ns:wave[@waveID="1"]');  
# so @n1 is an array of nodes with the waveID 1
# Above you are searching from the root of the tree,
# for element wave, with attribute waveID set to 1.
foreach $nod1 (@n1) {
# $nod1 is the name of the iterator,
# which iterates through the array @n1 of node values.
my @wellNames = $nod1->getElementsByTagName('well'); #element inside the tree.
# print out the wellNames :
foreach $well_name (@wellNames) {
print $well_name->textContent;
print "\n";
}

但我没有打印出 wellName,而是打印出 rawData 值(例如 0.1123975676)。我不明白为什么,你可以吗?我试图评论代码以帮助理解发生了什么,但如果评论不正确,请纠正我。谢谢。

最佳答案

假设您想要特定 wave 的所有 well 子级的 wellName 属性,用 XPath 表示而不是手动循环:

foreach my $n ($xc->findnodes(q<//ns:wave[@waveID='1']/ns:well/@wellName>)) {
print $n->textContent, "\n";
}

关于xml - 如何打印出属性值而不是元素内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2082400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com