简体   繁体   中英

How to read attributes in a XML file using nodes in SQL

I am trying to read ALL the Items from this XML using nodes but I jus manage to return just very first one, or none with the following examples.

How to read the entire list?

The file can contain hundreds of thousands.

XML file

<data source="1" target="0">
  <list item_nb="1">
    <co id="1" constitution="20190612101007" item_nb="44046">
      <item cm="640001000101" obu="00007E" vc="2" vrn="SOLD" />
      <item cm="640001000101" obu="00009D" vc="6" vrn="04D11797" />
      <item cm="640001000101" obu="0000A3" vc="2" vrn="FAULTY" />
      <item cm="640001000101" obu="00018B" vc="2" vrn="07D54084" />
      <item cm="640001000101" obu="0001A6" vc="6" vrn="000422" />
      <item cm="640001000101" obu="0001B2" vc="2" vrn="90D24430" />
      <item cm="640001000101" obu="0001B3" vc="2" vrn="03LS1592" />
      <item cm="640001000101" obu="0001B9" vc="6" vrn="FAULTYJUNE15" />
       </co>
  </list>
</data>

My Code in SQL (return only the first item)

declare @X xml;
select @X = T.MY_XML
from openrowset(bulk 'C:\XML\IEA.1.20190612101007-WL.XML', single_blob) as T(MY_XML)
select
   MY_XML.Item.value('(item/@cm)[1]', 'VARCHAR(20)'),
   MY_XML.Item.value('(item/@obu)[1]', 'VARCHAR(50)'),
   MY_XML.Item.value('(item/@vc)[1]', 'VARCHAR(50)'),
   MY_XML.Item.value('(item/@vrn)[1]', 'VARCHAR(50)')
from @X.nodes('data/list/co') AS MY_XML (Item);

found a way to work!

declare @X xml;
select @X = T.MY_XML
from openrowset(bulk 'C:\XML\IEA.1.20190612101007-WL.XML', single_blob) as T(MY_XML)
select
   MY_XML.Item.value('(@cm)[1]', 'VARCHAR(20)'),
   MY_XML.Item.value('(@obu)[1]', 'VARCHAR(50)'),
   MY_XML.Item.value('(@vc)[1]', 'VARCHAR(50)'),
   MY_XML.Item.value('(@vrn)[1]', 'VARCHAR(50)')
from @X.nodes('data/list/co/item') AS MY_XML (Item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM