2010-01-17 62 views
3

我有一个这样的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)。我看不出为什么,可以吗?我试着对代码发表评论以帮助理解发生了什么,但如果评论不正确,请纠正我。谢谢。

+0

你能给你的意思是“原始RAWDATA”什么的例子吗?你的意思是像一个参考,“标志(0×814f5c4)”? – 2010-01-17 20:14:27

+0

谢谢,我在问题中增加了更多细节。 – John 2010-01-17 20:17:27

+0

您会注意到XML包含一个“rawData”标记。 'textContent'打印出这个节点和所有子节点的文本内容(不是属性) - 换句话说,它应该打印出'0.1123975676' – 2010-01-17 20:18:07

回答

3

假设你想要的特定wave的所有well儿的wellName属性,表达了XPath,而不是用手循环:

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

+1。这是做这件事的正确方法。 – 2010-01-17 21:08:48

1

$node->attributes()返回属性节点列表。

另一种方法是直接使用XPath表达式获取属性节点,而不是使用XPath进行部分操作并手动完成其余部分。

+0

谢谢,我试过了,但它不起作用,你能帮忙请吗? my @test = $ nod1-> attributes(); #should返回属性节点列表 #现在从属性节点列表 中获取attribure wellName foreach $ t(@test){$ t-> getAttribute(wellName); – John 2010-01-17 20:57:32

+0

首先,您要在要获取属性的节点上调用'attributes'。其次,在libxml中没有'getAttribute()'方法 - 你需要迭代属性列表并调用'nodeName'来找到你想要的。 – 2010-01-17 21:08:21