How to remove xml nodes without attribute in Sql Server - sql

What is the correct way to remove all child nodes of the root node with a missing attribute from an xml field in Sql Server 2008?
My Xml looks like this, I want to remove all the child nodes of <root> that don't have the ln attribute specified
<root>
<title />
<title />
<questionphrase ln="nl">
<xhtml />
</questionphrase>
<questionphrase ln="en">
<xhtml />
</questionphrase>
<information ln="nl">
<xhtml />
</information>
<information ln="en">
<xhtml />
</information>
<title />
<title ln="en">
value
</title>
<label ln="en">
value
</label>
<title />
<title />
</root>
After the delete the xml should look like this
<root>
<questionphrase ln="nl">
<xhtml />
</questionphrase>
<questionphrase ln="en">
<xhtml />
</questionphrase>
<information ln="nl">
<xhtml />
</information>
<information ln="en">
<xhtml />
</information>
<title ln="en">
value
</title>
<label ln="en">
value
</label>
</root>

Try this:
DECLARE #xml XML = '....'
SET #xml.modify('delete //root/*[not(#ln)]')
SQL FIDDLE DEMO

Related

Post Array type of Xml data to Http calls

Hi i just want to know how to post xml data to Http post method in Objective-C by dynamically instead of static string Appending
here my sample xml Data :
<xml-packet version="2.5" ctr="1" timestamp="1345193301000">
<device id="0" name="hh" ipaddr="0.0.0.1" type="Hello" status="NORMAL"
capability="ios">
<devcice name="5s" type="2" status="NORMAL">
<sensor name="sample" type="" status="NORMAL">
<event timestamp="1345193300000" type="ITEM">
<position agid="3" name="Manager" lastsynctime="1344433367000" action="" />
<position agid="6" name="LOC3" lastsynctime="1343818867000" action="" />
<position agid="8" name="LOC5" lastsynctime="1344433367000" action="" />
<position agid="4" name="LOC1" lastsynctime="1344504045000" action="" />
<position agid="5" name="LOC2" lastsynctime="1343386683000" action="" />
<position agid="7" name="LOC4" lastsynctime="1344238182000" action="" />
</event>
<event timestamp="1345192938000" type="ITEM">
<position agid="1" name="CEO" lastsynctime="1344594202000" action="update">
<item id="ac001520101217000a012222" result="" status="NEW" lastmodifiedtime="" />
<item id="e20019838306016127500770" result="" status="NEW" lastmodifiedtime="" />
<item id="e20019838309014424301e64" result="" status="NEW" lastmodifiedtime="" />
<item id="2005790000000000000005fc" result="" status="MISSING" lastmodifiedtime="1345212728000" />
<item id="00000000012102007400bd39" result="" status="MISSING" lastmodifiedtime="1344594171000" />
</position>
</event>
</sensor>
</device>
</xml-packet>

Creating XML from MSSQL

How can I create the following XML from MS SQL?
I've looked and google and cant see for my specific example as below, thanks.
This would be from an SQL query using XML PATH in some manner.
<message>
<header date="15/07/2016" userid="QUOTEJOB">
<schema name="TKJobLoaderSchema" version="1.0" />
<source system="" product="" productversion="" />
<destination system="" product="" productversion="" />
</header>
<body>
<jobs>
<job action="jmCreate" company="02" contract="QW" description="test job" job_type="02" priority="5" created_by="QUOTEJOB">
<job_lines>
<job_line line_no="1" line_type="SOR" code="AQW" quantity="1916.5" />
</job_lines>
<job_narratives>
<job_narrative id="2" narrative="4678f874-314c-4584-99e3-c69e3af71999" />
</job_narratives>
<job_property company="02" ref="02363" />
</job>
</jobs>
</body>
</message>
Assuming, that every value is 1:1 your given sample can be created like the following (replace the literals with your actual column names, variables, whatever):
SELECT {d'2016-07-15'} AS [header/#date]
,'QUOTEJOB' AS [header/#userid]
,'TKJobLoaderSchema' AS [header/schema/#name]
,'1.0' AS [header/schema/#version]
,'' AS [header/source/#system]
,'' AS [header/source/#product]
,'' AS [header/source/#productversion]
,'' AS [header/destination/#system]
,'' AS [header/destination/#product]
,'' AS [header/destination/#productversion]
,'jmCreate' AS [body/jobs/job/#action]
,'02' AS [body/jobs/job/#company]
--more attributes of <job>
,1 AS [body/jobs/job/job_lines/job_line/#line_no]
--more attributes of <job_line>
,2 AS [body/jobs/job/job_narratives/job_narrative/#id]
--more attributes of <job_narrative>
,'02' AS [body/jobs/job/job_property/#company]
,'02363' AS [body/jobs/job/job_property/#ref]
FOR XML PATH('message')
The result
<message>
<header date="2016-07-15T00:00:00" userid="QUOTEJOB">
<schema name="TKJobLoaderSchema" version="1.0" />
<source system="" product="" productversion="" />
<destination system="" product="" productversion="" />
</header>
<body>
<jobs>
<job action="jmCreate" company="02">
<job_lines>
<job_line line_no="1" />
</job_lines>
<job_narratives>
<job_narrative id="2" />
</job_narratives>
<job_property company="02" ref="02363" />
</job>
</jobs>
</body>
</message>

Selecting values out of XML with SQL Server 2012 with nested namespaces

My XML looks like
<?xml version="1.0" encoding="UTF-8"?>
<ListasExternasFull xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Encabezado xmlns="http://tempuri.org/">
<Acceso>true</Acceso>
<Usuario>FENALCO</Usuario>
<Contrasena>FENALCO2015PROD</Contrasena>
<Documento>24944511</Documento>
<TipoDocumento>1</TipoDocumento>
<Nombres />
<Apellidos />
<Login />
<Fecha>2016-01-23T17:07:56.1986626-05:00</Fecha>
<IdConsulta>0</IdConsulta>
</Encabezado>
<objContraloria xmlns="http://tempuri.org/">
<Id>92798</Id>
<IsContraloria>false</IsContraloria>
<Cedula>24944511</Cedula>
<Nombre />
<Departamento />
<Municipio />
<EntidadAfectada />
<FallosACargo />
<TipoResponsabilidad />
<TipoPersona />
<ReportadoPor />
<FechaControl>2016-01-23T17:03:43.13</FechaControl>
<Excepcion />
</objContraloria>
<objFosyga xmlns="http://tempuri.org/">
<Id>92496</Id>
<IsFosyga>false</IsFosyga>
<NumeroIdentidad>24944511</NumeroIdentidad>
<Nombre />
<Apellido />
<Departamento />
<Municipio />
<Estado />
<Entidad />
<Regimen />
<FechaAfiliacion />
<TipoAfiliado />
<FechaControl>2016-01-23T17:07:56.285612-05:00</FechaControl>
<Excepcion>Se generó un error al consultar la lista. Por favor intente mas tarde o contacte a su administrador.</Excepcion>
</objFosyga>
<objOfac xmlns="http://tempuri.org/">
<Id>91950</Id>
<Cedula>24944511</Cedula>
<Nombre />
<Direccion />
<Tipo />
<Programa />
<Score />
<FechaControl>2016-01-23T17:03:43.097</FechaControl>
<Lista />
<Excepcion />
<IsOfac>false</IsOfac>
</objOfac>
<objPolicia xmlns="http://tempuri.org/">
<Id>93113</Id>
<Cedula>24944511</Cedula>
<Nombre />
<IsAntecedentes>false</IsAntecedentes>
<IsRegistrado>false</IsRegistrado>
<Mensaje />
<FechaControl>2016-01-23T17:08:17.3118339-05:00</FechaControl>
<IsPolicia>false</IsPolicia>
<Excepcion>Se generó un error al consultar la lista. Por favor intente mas tarde o contacte a su administrador.</Excepcion>
</objPolicia>
<objRues xmlns="http://tempuri.org/">
<Id>91297</Id>
<TipoID />
<Nit>24944511</Nit>
<RazonSocial />
<Descripcion_Camara />
<Descripcion_Categoria_Matricula />
<Fecha_Matricula />
<IsRM>false</IsRM>
<IsRUP>false</IsRUP>
<IsESAL>false</IsESAL>
<IsRNT>false</IsRNT>
<FechaControl>2016-01-23T17:03:43.473</FechaControl>
<IsRUES>false</IsRUES>
<Excepcion />
</objRues>
<objSim xmlns="http://tempuri.org/">
<Id>92657</Id>
<Cedula>24944511</Cedula>
<NoRadicado />
<Identificador />
<FechaSolicitud />
<Estado />
<Resultado />
<DisponibleEntrega />
<Excepcion />
<FechaControl>2016-01-23T17:03:43.207</FechaControl>
<IsSim>false</IsSim>
</objSim>
<objSimit xmlns="http://tempuri.org/">
<Id>92905</Id>
<Cedula>24944511</Cedula>
<Infractor />
<Resolucion />
<FechaResolucion />
<Comparendo />
<FechaComparendo />
<Secretaria />
<Estado />
<Infraccion />
<ValorMulta />
<InteresMora />
<ValorAdicional />
<ValorPagar />
<FechaControl>2016-01-23T17:03:43.55</FechaControl>
<IsSimit>false</IsSimit>
<Excepcion />
</objSimit>
<objSisben xmlns="http://tempuri.org/">
<Id>94783</Id>
<IsSisben>true</IsSisben>
<NumeroDocumento>24944511</NumeroDocumento>
<Nombres>MARIA ISLENY</Nombres>
<Apellidos>RODAS DE FRANCO</Apellidos>
<TipoDocumento>Cédula de Ciudadanía</TipoDocumento>
<Departamento>RISARALDA</Departamento>
<Municipio>PEREIRA</Municipio>
<Area>1</Area>
<Ficha>10097</Ficha>
<Puntaje>47,86</Puntaje>
<FechaModificacion>2015/03/05</FechaModificacion>
<Estado>VALIDADO</Estado>
<FechaControl>2016-01-23T17:03:43.287</FechaControl>
<Excepcion />
</objSisben>
<objRuaf xmlns="http://tempuri.org/">
<Id>84066</Id>
<IsRuaf>true</IsRuaf>
<TipoIdentificacion>CC</TipoIdentificacion>
<Identificacion>24944511</Identificacion>
<Nombre>MARIA ISLENY RODAS DE FRANCO</Nombre>
<Sexo>FEMENINO</Sexo>
<UbicacionAfiliacion>RISARALDA - PEREIRA</UbicacionAfiliacion>
<EstadoAfiliado>ACTIVO</EstadoAfiliado>
<Administradora>NUEVA EPS SA</Administradora>
<Regimen>SALUD: CONTRIBUTIVO</Regimen>
<FechaAfiliacion>2015-08-01</FechaAfiliacion>
<TipoAfiliado>BENEFICIARIO</TipoAfiliado>
<FechaControl>2016-01-23T17:03:45.207</FechaControl>
<Observacion />
<Excepcion />
</objRuaf>
<objDisponibilidad xmlns="http://tempuri.org/">
<Fosyga>true</Fosyga>
<Sisben>true</Sisben>
<Ofac>true</Ofac>
<Policia>true</Policia>
<Rues>true</Rues>
<Sim>true</Sim>
<Simit>true</Simit>
<Contraloria>true</Contraloria>
<Onu>true</Onu>
<Ruaf>true</Ruaf>
</objDisponibilidad>
</ListasExternasFull>
and I can not get reach to consult the objRuaf/Identificacion node due to nested namespaces aguin I can help with a query to reach these nodes
Declare default XML namespace WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/'):
;WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/')
SELECT val = s.c.value('.', 'NVARCHAR(100)')
FROM #x.nodes('//objRuaf/Identificacion') AS s(c);
LiveDemo
Or:
;WITH XMLNAMESPACES ('http://tempuri.org/' AS a)
SELECT val = s.c.value('.', 'NVARCHAR(100)')
FROM #x.nodes('//a:objRuaf/a:Identificacion') AS s(c)

SQL XML load with OpenRow

I am trying to load a XML document (below is an example of how I receive the files. I can read the xml, but I am unable to insert the the data into tables. Any help would be appreciative.
<xml xmlns:dt="urn:dt" xmlns:msxsl="urn:schemas-microsoft-com:xslt" dateofservice="1/1/2016 10:00" mmsid="201599999999" userid="dxxxxx9-xxx0-xxdb-xxx0-e8xxxxxxbcd" npid="dfxxxxx9-6xx0-xxxx-bxx0-exxxc1xxxxxd" surveyid="xxxxxxx-xxxa-exxx-8xxx-xxxx56xxxxefb" memberid="sqlsrfr">
<response qid="801" debug="7" value="H" element="select" />
<response qid="150" debug="8" value="Surfer" element="input" mapfield="lastname" />
<response qid="109" debug="9" value="Sequel" element="input" mapfield="firstname" />
<response qid="57" debug="11" value="01/01/1901" element="input" mapfield="dob" />
<response qid="56" debug="12" value="M" element="input" type="radio" aid="85" />
<response qid="78" debug="13" value="123 Sequel Lane" element="textarea" mapfield="addr1" />
<response qid="126" debug="39" value="Stuff" element="input" row="9" placeholder="Placeholder Desc" customtype="disabled" />
<response qid="128" debug="40" value="Stuff" element="input" row="9" placeholder="Placeholder Desc" customtype="disabled" />
<response qid="305" debug="41" value="More words" element="input" row="9" placeholder="Placeholder Desc" customtype="normal" />
<response qid="579" debug="330" value="1" element="input" type="radio" />
<response qid="580" debug="331" value="1" element="input" type="radio" />
<response qid="716" value="Words for value" calc="1" screening="1" />
<response qid="779" value="More words for value" calc="1" highriskdrug="1" />
- <surveyevents>
<event name="Event Name 2.0.3.7" time="1451495565657" count="1" />
<event name="s2" time="1451495568305" count="2" last="1451495728416" />
<event name="s3" time="1451495577298" count="1" />
<event name="s18" time="1451495601418" count="1" />
<event name="Event Name 2.0.3.7" time="1451495725279" count="1" />
<event name="Event Name 2.0.4.1" time="1453394485181" count="1" />
</surveyevents>
<recapturedata />
</xml>
Given, that you manage to read the XML into a variable, the full (de-normalized) query is this:
You will have to design three tables for MetaData, ResponseData and EventData and insert your data there.
If you need to create kind of IDs have a look on ROW_NUMBER() OVER()
btw: The declared namespaces are not used... and define the fitting datatypes yourself (I took only varchar(max) or int).
WITH XMLNAMESPACES('urn:dt' AS dt
,'urn:schemas-microsoft-com:xslt' AS msxsl)
,MetaData AS
(
SELECT #xml.value('/xml[1]/#dateofservice','varchar(max)') AS md_DateOfService
,#xml.value('/xml[1]/#mmsid','varchar(max)') AS md_MmsID
,#xml.value('/xml[1]/#userid','varchar(max)') AS md_UserID
,#xml.value('/xml[1]/#npid','varchar(max)') AS md_NpID
,#xml.value('/xml[1]/#surveyid','varchar(max)') AS md_SurveyID
,#xml.value('/xml[1]/#memberid','varchar(max)') AS md_MemberID
,#xml.query('.') AS XMLNode
)
SELECT md.md_DateOfService
,md.md_MmsID
,md.md_UserID
,md.md_NpID
,md.md_SurveyID
,md.md_MemberID
,response.value('#qid','int') AS resp_qID
,response.value('#debug','int') AS resp_Debug
,response.value('#value','varchar(max)') AS resp_Value
,response.value('#element','varchar(max)') AS resp_Element
,response.value('#row','int') AS resp_Row
,response.value('#mapfield','varchar(max)') AS resp_MapField
,response.value('#type','varchar(max)') AS resp_Type
,response.value('#aid','int') AS resp_aID
,response.value('#placeholder','varchar(max)') AS resp_Placeholder
,response.value('#customtype','varchar(max)') AS resp_CustomType
,EventRow.value('#name','varchar(max)') AS evnt_Name
,EventRow.value('#time','varchar(max)') AS evnt_Time
,EventRow.value('#count','int') AS evnt_Count
,EventRow.value('#last','varchar(max)') AS evnt_Last
FROM MetaData AS md
CROSS APPLY md.XMLNode.nodes('/xml/response') AS One(response)
CROSS APPLY md.XMLNode.nodes('/xml/surveyevents/event') AS The(EventRow)

How to get value from XML in stored procedure?

Can you all help me for this problem?
I want to get value from following XML in sql stored procedure. I don't get vlaue if 'xsi:type="ActiveDirectoryItem"' is in tag 'anyType', and 'ActiveDirectoryItems' tag is also with URLs. How can i do to get only values?
<?xml version="1.0" encoding="utf-8" ?>
<ActiveDirectoryItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Items>
<anyType xsi:type="ActiveDirectoryItem">
<FirstName />
<MiddleInitial />
<LastName />
<DisplayName>Migrate-group</DisplayName>
<UserPrincipalName />
<PostalAddress />
<ResidentialAddress />
<Title />
<HomePhone />
<OfficePhone />
<Mobile />
<Fax />
<Email>Migrate-group#gmail.com</Email>
<Url />
<AccountName>Migrate-group</AccountName>
<DistinguishedName />
<IsAccountActive>false</IsAccountActive>
<ManagedBy />
<Manager />
<CompareType>0</CompareType>
<Description />
<Department />
<Company />
<Type />
</anyType>
</Items>
<GlobalCatalog />
</ActiveDirectoryItems>
The format i want to get is as the following:
DisplayName Email Account Name
Migrate-group Migrate-group#gmail.com Migrate-group
you can use the value keyword
Example:
DECLARE #MyXml XML = '<Root><SomeData>100</SomeData></Root>'
DECLARE #Something INT
SELECT #Something = #MyXml.value('(//Root/SomeData)[1]', 'INT')