Advertisement
qwe43tgdff32

Groovy xxml

Jun 25th, 2024
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 2.21 KB | Jokes | 0 0
  1. import groovy.xml.StreamingMarkupBuilder
  2. import groovy.xml.XmlSlurper
  3. import groovy.xml.XmlUtil
  4.  
  5. def xml = '''<?xml version="1.0" encoding="UTF-8"?>
  6. <Record>
  7.   <XYZ>
  8.      <Header>
  9.         <Code>12345</Code>
  10.      </Header>
  11.      <Details>
  12.         <RecID>1</RecID>
  13.         <RecordDetail>
  14.            <Name>ABC</Name>
  15.            <Email>[email protected]</Email>
  16.            <Address>123,acdf</Address>
  17.         </RecordDetail>
  18.      </Details>
  19.      <Details>
  20.         <RecID>2</RecID>
  21.         <RecordDetail>
  22.            <Name>ABC</Name>
  23.            <Email>[email protected]</Email>
  24.         </RecordDetail>
  25.      </Details>
  26.   </XYZ>
  27. </Record>'''
  28.  
  29. def parsedXml = new XmlSlurper().parseText(xml)
  30.  
  31. def builder = new StreamingMarkupBuilder()
  32. builder.encoding = 'UTF-8'
  33. def transformedXml = builder.bind {
  34.   mkp.xmlDeclaration()
  35.   Record {
  36.     Header {
  37.       Code (parsedXml.'**'.find{ it.name() == 'Code'})
  38.     }
  39.     def details = parsedXml.'**'.findAll{ it.name() == 'Details'}
  40.     details.each { detail ->
  41.       Details {
  42.         RecID (detail.RecID)
  43.         detail.RecordDetail.children().each { fld ->
  44.           RecordDetail {
  45.             FieldName (fld.name())
  46.             FieldValue (fld.text())
  47.           }
  48.         }
  49.       }
  50.     }
  51.   }
  52. }
  53.  
  54. println XmlUtil.serialize(transformedXml)
  55.  
  56.  
  57. //// output
  58. <?xml version="1.0" encoding="UTF-8"?><Record>
  59.   <Header>
  60.     <Code>
  61.       <Code>12345</Code>
  62.     </Code>
  63.   </Header>
  64.   <Details>
  65.     <RecID>
  66.       <RecID>1</RecID>
  67.     </RecID>
  68.     <RecordDetail>
  69.       <FieldName>Name</FieldName>
  70.       <FieldValue>ABC</FieldValue>
  71.     </RecordDetail>
  72.     <RecordDetail>
  73.       <FieldName>Email</FieldName>
  74.       <FieldValue>abc@in.com</FieldValue>
  75.     </RecordDetail>
  76.     <RecordDetail>
  77.       <FieldName>Address</FieldName>
  78.       <FieldValue>123,acdf</FieldValue>
  79.     </RecordDetail>
  80.   </Details>
  81.   <Details>
  82.     <RecID>
  83.       <RecID>2</RecID>
  84.     </RecID>
  85.     <RecordDetail>
  86.       <FieldName>Name</FieldName>
  87.       <FieldValue>ABC</FieldValue>
  88.     </RecordDetail>
  89.     <RecordDetail>
  90.       <FieldName>Email</FieldName>
  91.       <FieldValue>abc@in.com</FieldValue>
  92.     </RecordDetail>
  93.   </Details>
  94. </Record>
  95.  
  96.  
  97. Process finished with exit code 0
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement