2013-06-13 70 views
2

我有一個類似於下面的XML,並且試圖根據關鍵字提取節點。 嘗試使用XPath和XMLLint。但顯然,我沒有做正確的事情。所以 希望在這方面有所幫助。基於關鍵字從xml中提取節點

鑑於這種XML和關鍵字Task objectivesobjectives(案例 不敏感),我需要提取整個節點,並寫入到另一個XML文件

<section> 
    <h1>2 Task objectives</h1> 
    <region>2.1 Primary objectives </region> 
    <region>2.</region> 
</section> 

提取XML文件

<section> 
    <h>2 Introduction</h1> 
    <region>Intro 1</region> 
    <region>Background</region> 
    </section> 
<article> 
<body> 
    <section> 
    <h1>2 Task objectives</h1> 
    <region>2.1 Primary objectives </region> 
    <region>2.</region> 
    </section> 

    <section> 
    <h2>Requirements</h1> 
    <region>System Requirements </region> 
    <region>Technical Requirements</region> 
    </section> 

    <section> 
    <h3>Design</h1> 
    <region>Design methodology </region> 
    <region>Design patterns</region> 
    </section> 
    </body> 
</article> 

我嘗試使用Xpath和XMllint。

$ xmllint --xpath //body//section//h1[.="Task objectives"] Prior.mod.xml 
XPath error : Invalid predicate 
//body//section//h1[.=Task objectives] 
       ^
xmlXPathEval: evaluation failed 
XPath evaluation failure 

任何人都可以請讓我知道什麼是錯的上面,我怎麼能解決 呢?另外,我想在一個文件目錄的shell中執行此操作。 XMLlint是最佳選擇 ?

回答

2

外殼採用命令行解析過程中除去引號(")字符 - 你需要引用整個表達式,如在

xmllint --xpath '//body//section//h1[.="Task objectives"]' Prior.mod.xml 

實施例:

$ xmllint --xpath //body//section//h1[.="Task objectives"] - 
<body> 
<section> 
<h1>Task objectives</h1> 
<h1>abcd</h1> 
</section> 
</body> 
^D 

從而造成:

XPath error : Invalid predicate 
//body//section//h1[.=Task objectives] 
         ^
xmlXPathEval: evaluation failed 
XPath evaluation failure 

請注意缺少的引號。然後,我嘗試

$ xmllint --xpath '//body//section//h1[.="Task objectives"]' - 
<body> 
<section> 
<h1>Task objectives</h1> 
<h1>abcd</h1> 
</section> 
</body> 
^D 

其產生的輸出

<h1>Task objectives</h1> 
+0

由於這個工作。 – BRZ

0

這對我的作品使用XPath 1.0:

//section[contains(
    translate(h1, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 
    'task objectives') 
]