2012-06-19 119 views
2

我对XPath有点新手,所以我需要一些帮助来解决这个问题。我有这样的XML文件:在嵌套节点中获取唯一的XPath节点值

<items> 
    <item> 
     <brandName>Brand 1</brandName> 
     <productTypes> 
      <productType>Type 1</productType> 
      <productType>Type 3</productType> 
     </productTypes> 
    </item> 
    <item> 
     <brandName>Brand 1</brandName> 
     <productTypes> 
      <productType>Type 2</productType> 
      <productType>Type 3</productType> 
     </productTypes> 
    </item> 
    <item> 
     <brandName>Brand 2</brandName> 
     <productTypes> 
      <productType>Type 4</productType> 
      <productType>Type 5</productType> 
     </productTypes> 
    </item> 
</items> 

我试图找出一种方法来获取特定品牌的所有独特productType。例如,“品牌1”的所有唯一productType将输出“类型1”,“类型2”,“类型3”

我一直在使用Google,但没有多少运气。任何帮助,将不胜感激!

+0

我不认为你可以在一个节点集XPath表达式进行独特的操作,你需要在任何一种语言,你使用的解析表达式一些额外的代码。 – jspboix

回答

3

这工作:

(/items/item[brandName='Brand 1']/productTypes/productType)[not(text()=preceding::*)] 

它是如何工作:第一(...)获得名优产品= '品牌1' 的所有productType。在这一点上,我有一个productType节点的列表。现在,我选择节点文本未包含在当前节点之前的节点中的节点。

尝试在Python:

n = libxml2dom.parseString(xml) 
[x.textContent for x in n.xpath("(/items/item[brandName='Brand 1']/productTypes/productType)[not(text()=preceding::*)]")] 
>>> [u'Type 1', u'Type 3', u'Type 2'] 
+0

工作就像一个魅力,谢谢你! –