我有一个多个xml文档,如下所示:
<farm>
<name>Johns Farm</name>
<size>50 hectares</size>
<employees>20</employees>
<fruits>
<fruit>Banana</fruit>
<fruit>Apple</fruit>
<fruit>Watermelon</fruit>
</fruits>
</farm>
我在这样的oracle数据库中得到了这个:
CREATE TABLE FARM_XML_TABLE
(FARM_NUMBER NUMBER NOT NULL PRIMARY KEY, FARM_XML XMLTYPE NOT NULL)
XMLTYPE COLUMN FARM_XML STORE AS BINARY XML
XMLSCHEMA
"http://myproject.com/farmschema.xsd"
ELEMENT "farm";
各种农场存储在FARM_XML
列中。其中大约有5个
如何以XML格式从多个服务器场的FARM_XML
列中仅检索名称和员工元素。我希望输出像这样:
<farm>
<name>Johns Farm</name>
<employees>20</employees>
</farm>
<farm>
<name>Harrys Farm</name>
<employees>10</employees>
</farm>
我尝试过这样做,但输出并不是我想要的所有xml元素。
SELECT extract(FARM_XML, 'farm/name').getStringVal()
FROM FARM_XML_TABLE;
答案 0 :(得分:3)
Oracle安装程序:
CREATE TABLE FARM_XML_TABLE(
FARM_NUMBER NUMBER PRIMARY KEY,
FARM_XML XMLTYPE NOT NULL
)
XMLTYPE COLUMN FARM_XML STORE AS BINARY XML;
INSERT INTO FARM_XML_TABLE VALUES(
1,
XMLtype( '<farm>
<name>Johns Farm</name>
<size>50 hectares</size>
<employees>20</employees>
<fruits>
<fruit>Banana</fruit>
<fruit>Apple</fruit>
<fruit>Watermelon</fruit>
</fruits>
</farm>' )
);
查询1 - 重建XML :
SELECT FARM_NUMBER,
XMLElement(
"farm",
XMLElement( "name", EXTRACTVALUE( farm_xml, '/farm/name' ) ),
XMLElement( "employees", EXTRACTVALUE( farm_xml, '/farm/employees' ) )
) AS xml
FROM FARM_XML_TABLE;
或(更新 - 更简单的版本):
SELECT FARM_NUMBER,
XMLElement(
"farm",
EXTRACT( farm_xml, '/farm/name' ),
EXTRACT( farm_xml, '/farm/employees' )
) AS xml
FROM FARM_XML_TABLE;
查询2 - 从现有XML中删除不匹配的元素:
SELECT FARM_NUMBER,
DELETEXML(
farm_xml,
'/farm/*[name()!=''name''][name()!=''employees'']'
) AS xml
FROM FARM_XML_TABLE;
<强>输出强>:
(两者输出相同)
FARM_NUMBER XML
----------- -------------------------------------------------------------
1 <farm><name>Johns Farm</name><employees>20</employees></farm>