我正在使用一個巨大的 xml 檔案,我需要獲取 500 個節點的樣本,這些節點是根節點的直接子節點。我知道它們屬于同一型別。我需要得到這 500 個節點的所有子節點。
有辦法這樣做xmlstarlet嗎?
我更喜歡使用這個特定的包,因為我已經在使用它來對同一檔案進行其他操作。
我嘗試查看包的幫助頁面,但找不到方法
uj5u.com熱心網友回復:
你可以試試:
xmlstarlet sel -t -c "/root/child[position() <= 500]" file.xml
sel是查詢 XML 的標準方法-t使用時總是需要sel-c用于復制(
無論您在 xpath 中下一步選擇什么)/root/child是xpath
(顯然替換為實際元素名稱)[position() <= 500]選擇位置(在根元素內)為 500 或更小的所有節點。
有時,我發現將路徑括在括號中可以使選擇起作用:
xmlstarlet sel -t -c "(/root/child)[position() <= 500]" file.xml
但一般來說,第一種方法就足夠了。
所以,給定一個輸入:
<root>
<child>...</child>
<child>...</child>
...
</root>
你會得到:
<child>...</child><child>...</child>...
請注意,沒有語法上有效的 XML。
要使用換行符分隔,請嘗試以下變體:
xmlstarlet sel -t -m "/root/child[position() <= 500]" -c "." -n file.xml
-m只是m匹配 xpath
(不產生輸出)-c "."復制匹配的節點-n在每個匹配/復制的節點之后附加一個新行
第 2 部分 - 選擇某種型別的前“n”個節點
假設您想從以下 XML('example.xml')中獲取前 3 個蘋果:
<root>
<apple>Braeburn</apple>
<banana>Chiquita</banana>
<apple>Granny Smith</apple>
<plantain/>
<apple>Cox</apple>
<apple>Elstar</apple>
<apple/>
<apple/>
</root>
然后你可以使用:
xmlstarlet sel -t -m "/root/apple[position() <= 3]" -c "." -n example.xml
這又與前面的例子基本相同。
通過添加元素名稱 ('apple'),您將專門選擇前三個蘋果節點,如以下輸出所示:
<apple>Braeburn</apple>
<apple>Granny Smith</apple>
<apple>Cox</apple>
請注意如何<banana>Chiquita</banana>和<plantain/>被遺漏。
他們不是<root/>type 的直接孩子<apple/>。
獎金:
假設您想獲得第三個蘋果,那么您可以使用:
xmlstarlet sel -t -c "/root/apple[position() = 3]" example.xml
這會給你:<apple>Cox</apple>。
甚至更短:
xmlstarlet sel -t -c "/root/apple[3]" example.xml
再次給你同樣的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529590.html
