postgresql:xml解析:xpath只返回一条记录,其中xml包含3条记录

时间:2014-08-31 06:31:53

标签: sql xml postgresql xml-parsing

我在postgresql中有一个xml类型参数的过程。 我需要解析xml并在表中插入记录。 我试过这种方式,但它只在表中插入一条记录,其中xml包含三条记录。

xml代码是

Select (xpath('/ArrayOfUserGroupModulePermissionBusinessObject/UserGroupModulePermissionBusinessObject/ModuleID/text()', t1))[1]::varchar::BIGINT AS ModuleID
from (Select Perms::xml as t1) as t2;

xml在这里

<ArrayOfUserGroupModulePermissionBusinessObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <UserGroupModulePermissionBusinessObject>
    <UserGroupModulePermissionID>0</UserGroupModulePermissionID>
    <UserGroupID>0</UserGroupID>
    <ModuleID>3</ModuleID>
    <ModuleName>Administration</ModuleName>
    <CanRead>false</CanRead>
    <CanAdd>false</CanAdd>
    <CanEdit>false</CanEdit>
    <CanDelete>false</CanDelete>
    <CanPrint>false</CanPrint>
  </UserGroupModulePermissionBusinessObject>
  <UserGroupModulePermissionBusinessObject>
    <UserGroupModulePermissionID>0</UserGroupModulePermissionID>
    <UserGroupID>0</UserGroupID>
    <ModuleID>2</ModuleID>
    <ModuleName>Data Management</ModuleName>
    <CanRead>false</CanRead>
    <CanAdd>false</CanAdd>
    <CanEdit>false</CanEdit>
    <CanDelete>false</CanDelete>
    <CanPrint>false</CanPrint>
  </UserGroupModulePermissionBusinessObject>
  <UserGroupModulePermissionBusinessObject>
    <UserGroupModulePermissionID>0</UserGroupModulePermissionID>
    <UserGroupID>0</UserGroupID>
    <ModuleID>1</ModuleID>
    <ModuleName>Reception</ModuleName>
    <CanRead>false</CanRead>
    <CanAdd>false</CanAdd>
    <CanEdit>false</CanEdit>
    <CanDelete>false</CanDelete>
    <CanPrint>false</CanPrint>
  </UserGroupModulePermissionBusinessObject>
</ArrayOfUserGroupModulePermissionBusinessObject>

我不知道这个sql有什么问题

1 个答案:

答案 0 :(得分:2)

xpath函数返回一个数组,其中包含每个结果的元素。您只使用数组中的第一个元素,而数组实际上包含您期望的所有三个元素。使用unnest将数组转换为行。

Select unnest(xpath('/ArrayOfUserGroupModulePermissionBusinessObject/UserGroupModulePermissionBusinessObject/ModuleID/text()', t1))::varchar::BIGINT AS ModuleID
from (Select Perms::xml as t1) as t2;