相对xpath位置上的PostgreSQL绝对
考虑存储在PostgreSQL字段中的以下xml文档:相对xpath位置上的PostgreSQL绝对,postgresql,xpath,Postgresql,Xpath,考虑存储在PostgreSQL字段中的以下xml文档: <E_sProcedure xmlns="http://www.minushabens.com/2008/FMSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" modelCodeScheme="Emo_ex" modelCodeSchemeVersion="01" modelCod
<E_sProcedure xmlns="http://www.minushabens.com/2008/FMSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" modelCodeScheme="Emo_ex" modelCodeSchemeVersion="01" modelCodeValue="EMO_E_PROCEDURA" modelCodeMeaning="Section" sectionID="11">
<tCatSnVsn_Pmax modelCodeScheme="Emodinamica_referto" modelCodeSchemeVersion="01" modelCodeValue="tCat4" modelCodeMeaning="My text"><![CDATA[1]]></tCatSnVsn_Pmax>
</E_sProcedure>
第2行的xpath有什么问题?由于两个问题,您的第二个xpath()没有返回任何内容。第一:您需要使用//tCatSnVsn\u Pmax
,因为xml\u元素仍然以
开头。路径/tCatSnVsn\u Pmax
尝试选择具有该名称的顶级元素
但即使这样,第二个也不会因为名称空间而返回任何内容。您需要将相同的名称空间定义传递给xpath(),因此需要如下内容:
SELECT (xpath('/x:tCatSnVsn_Pmax/text()', t.xml_element, ARRAY[ARRAY['x', 'http://www.minushabens.com/2008/FMSchema']]))[1] as tCatSnVsn_Pmax
FROM (
SELECT unnest(xpath('//x:E_sProcedure', s.XMLDATA::xml, ARRAY[ARRAY['x', 'http://www.minushabens.com/2008/FMSchema']])) AS xml_element
FROM sr_data as s
)t;
对于现代Postgres版本(>=10),我更喜欢使用xmltable()
来处理任何不寻常的事情。它使传递名称空间和访问多个属性或元素变得更容易
SELECT xt.*
FROM sr_data
cross join
xmltable(xmlnamespaces ('http://www.minushabens.com/2008/FMSchema' as x),
'/x:E_sProcedure'
passing (xmldata::xml)
columns
sectionid text path '@sectionID',
pmax text path 'x:tCatSnVsn_Pmax',
model_code_value text path 'x:tCatSnVsn_Pmax/@modelCodeValue') as xt
对于示例XML,上面返回:
sectionid | pmax | model |代码|值
----------+------+-----------------
11 | 1 | tCat4
由于两个问题,您的第二个xpath()没有返回任何内容。第一:您需要使用//tCatSnVsn\u Pmax
,因为xml\u元素仍然以
开头。路径/tCatSnVsn\u Pmax
尝试选择具有该名称的顶级元素
但即使这样,第二个也不会因为名称空间而返回任何内容。您需要将相同的名称空间定义传递给xpath(),因此需要如下内容:
SELECT (xpath('/x:tCatSnVsn_Pmax/text()', t.xml_element, ARRAY[ARRAY['x', 'http://www.minushabens.com/2008/FMSchema']]))[1] as tCatSnVsn_Pmax
FROM (
SELECT unnest(xpath('//x:E_sProcedure', s.XMLDATA::xml, ARRAY[ARRAY['x', 'http://www.minushabens.com/2008/FMSchema']])) AS xml_element
FROM sr_data as s
)t;
对于现代Postgres版本(>=10),我更喜欢使用xmltable()
来处理任何不寻常的事情。它使传递名称空间和访问多个属性或元素变得更容易
SELECT xt.*
FROM sr_data
cross join
xmltable(xmlnamespaces ('http://www.minushabens.com/2008/FMSchema' as x),
'/x:E_sProcedure'
passing (xmldata::xml)
columns
sectionid text path '@sectionID',
pmax text path 'x:tCatSnVsn_Pmax',
model_code_value text path 'x:tCatSnVsn_Pmax/@modelCodeValue') as xt
对于示例XML,上面返回:
sectionid | pmax | model |代码|值
----------+------+-----------------
11 | 1 | tCat4