2011-01-29 112 views
188

如何通過XPath提取屬性節點的值?通過XPath提取屬性節點的值

示例XML文件是:

<parents name='Parents'> 
    <Parent id='1' name='Parent_1'> 
    <Children name='Children'> 
     <child name='Child_2' id='2'>child2_Parent_1</child> 
     <child name='Child_4' id='4'>child4_Parent_1</child> 
     <child name='Child_1' id='3'>child1_Parent_1</child> 
     <child name='Child_3' id='1'>child3_Parent_1</child> 
    </Children> 
    </Parent> 
    <Parent id='2' name='Parent_2'> 
    <Children name='Children'> 
     <child name='Child_1' id='8'>child1_parent2</child> 
     <child name='Child_2' id='7'>child2_parent2</child> 
     <child name='Child_4' id='6'>child4_parent2</child> 
     <child name='Child_3' id='5'>child3_parent2</child> 
    </Children> 
    </Parent> 
</parents> 

到目前爲止,我有這個XPath字符串:

//Parent[@id='1']/Children/child[@name] 

它只返回child元素,但我想有name屬性的值。

在我的示例XML文件,這裏是想我的輸出是:

Child_2 
Child_4 
Child_1 
Child_3 
+0

[使用XPath獲取屬性](http:// stackoverflow。com/questions/4531995/getting-attribute-using-xpath) – tripleee 2015-12-03 08:53:13

回答

254
//Parent[@id='1']/Children/child/@name 

你原來child[@name]意味着一個元素child它有一個屬性name。您需要child/@name

+13

我同意,問題是如何獲取屬性的值 – Vladtn 2013-04-16 19:24:15

+3

如果我只想提取標籤之間存在的值/描述/數據,該怎麼辦? ... – 2017-02-22 07:52:13

1

@ryenus,你需要遍歷結果。這是我如何在VBScript中做到這一點;

Set xmlDoc = CreateObject("Msxml2.DOMDocument") 
xmlDoc.setProperty "SelectionLanguage", "XPath" 
xmlDoc.load("kids.xml") 

'Remove the id=1 attribute on Parent to return all child names for all Parent nodes 
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name") 
    Wscript.Echo c.text 
Next 
101

得到公正的價值(無屬性名稱),使用string()

string(//Parent[@id='1']/Children/child/@name)

fn:string()溫控功能將返回其參數的值作爲xs:string。如果它的參數是一個屬性,它將因此返回該屬性的值爲xs:string

+1

'xqilla`有必要調用`xs:string`。我想知道爲什麼。 – krlmlr 2013-07-22 20:00:11

3
//Parent/Children[@ Attribute='value']/@Attribute 

這是可以使用的情況下,其中元素有2個屬性,我們可以得到一個屬性與另一個幫助。

5

您應該使用//Parent[@id='1']/Children/child/data(@name)

的屬性不能被序列化,所以你不能在一個XML尋找結果回報他們。你需要做的是使用data()函數從屬性獲取數據。

5

如以上回答:

//Parent[@id='1']/Children/child/@name 

將只輸出屬於由它的謂詞[@ ID = 1]中指定的Parent 4個child節點的name屬性。然後,您需要將謂詞更改爲[@id=2]以獲取下一個Parentchild節點集。

但是,如果完全忽略了Parent節點及用途:

//child/@name 

可以一氣呵成選擇所有child節點name屬性。

name="Child_2" 
name="Child_4" 
name="Child_1" 
name="Child_3" 
name="Child_1" 
name="Child_2" 
name="Child_4" 
name="Child_3"