2010-01-17 63 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