2011-11-22 3 views
2

XPath 쿼리에서 여러 계층 수준의 값 을 동시에 표시하려는 PostgreSQL에 어떻게 표현할 수 있습니까?상위 계층과 하위 관계를 보존하는 계층 적 데이터로 XPath 쿼리

다단계 계층 구조가있는 문서 (PostgreSQL XML 값)가 있습니다. 이 질문의 경우 다음을 사용하여 예제를 만들 수 있습니다.

SELECT XMLPARSE(DOCUMENT ' 
    <parrots> 
     <parrot name="Fred"> 
      <descriptor>Beautiful plumage</descriptor> 
      <descriptor>Resting</descriptor> 
     </parrot> 
     <parrot name="Ethel"> 
      <descriptor>Pining for the fjords</descriptor> 
      <descriptor>Stunned</descriptor> 
     </parrot> 
    </parrots> 
    ') AS document 
INTO TEMPORARY TABLE parrot_xml; 

해당 문서에서 다른 수준의 정보를 얻을 수 있습니다. 내가 알아낼 수 없습니다 무엇

=> SELECT 
     (XPATH('./@name', parrot.node))[1] AS name 
    FROM (    
     SELECT 
      UNNEST(XPATH('./parrot', parrot_xml.document)) 
       AS node 
     FROM parrot_xml 
     ) AS parrot 
    ; 
name 
------- 
Fred 
Ethel 
(2 rows) 

=> SELECT 
     (XPATH('./text()', descriptor.node))[1] AS descriptor 
    FROM (
     SELECT 
      UNNEST(XPATH('./parrot/descriptor', parrot_xml.document)) 
       AS node 
     FROM parrot_xml 
     ) AS descriptor 
    ; 
     descriptor  
----------------------- 
Beautiful plumage 
Resting 
Pining for the fjords 
Stunned 
(4 rows) 

하지만, 쿼리가 적용되는 앵무새와 관련된 각 기술자를 반환하도록, 여러 수준의 합류 얻는 방법이다.

=> SELECT 
     ??? AS name, 
     ??? AS descriptor 
    FROM 
     ??? 
    ; 
name   descriptor  
------- ----------------------- 
Fred Beautiful plumage  
Fred Resting    
Ethel Pining for the fjords 
Ethel Stunned    
(4 rows) 

어떻게

이 수행 할 수 있습니다? "???"의 자리에는 무엇이 있어야합니까?

단일 복합 XPath 쿼리 - 한 번에 여러 수준을 참조하는 방법은 무엇입니까? 여러 XPath 쿼리 - 그렇다면 결과 관계에 대해 조상 - 자손 정보가 어떻게 보존됩니까? 다른 것?

답변

4

이 시도 :

SELECT (xpath('./@name', parrot.node))[1] AS name 
    , unnest(xpath('./descriptor/text()', parrot.node)) AS descriptor 
FROM (    
    SELECT unnest(xpath('./parrot', parrot_xml.document)) AS node 
    FROM parrot_xml 
    ) parrot; 

정확히 요청 된 출력을 생성합니다.

먼저 하위 쿼리에서 전체 앵무 노드를 검색합니다. 행당 하나의 노드.

다음으로 xpath()를 사용하여 이름과 설명자를 얻습니다. 둘 다 배열입니다. 난 name의 첫 번째 (그리고 유일한) 요소를 취하고 descriptor 배열을`unnest()와 쪼개어 원하는 결과를 얻는다.

나는 최근에 comprehensive answer to a related question이라고 썼습니다. 관심이있을 수 있습니다.

+0

매우 훌륭하지만, PostgreSQL으로 XML을 처리하는 데 따른 제한 사항을 보여줍니다. 흠. ''옵션을 가진'xslt_process()'는 완벽 할 것이다 :-). –

관련 문제