cancel
Showing results for 
Search instead for 
Did you mean: 

how to convert xml file to a string and write that string to another XML file format in XI/PI?

0 Kudos

Hi Experts,

I have a requirement in that i need to convert the xml file in to a string and then write it to another file as valid xml format.

i tried few logics but all of those are failed to write converted string to xml file format as it is always taking that string as XML tags but not as a string.

for example my xml was


<?xml version="1.0" encoding="UTF-8"?>

<Students>

<Student_Name>Srinivas</Student_Name>

<Student_FullName>Srinivas_Kumar</Student_FullName>

<DOB>1992-09-25</DOB>

<FlatNo>#04, 8th main</FlatNo>

<Locality>Gandhi Road</Locality>

</Students>

expected output should be like


<?xml version="1.0" encoding="UTF-8"?>

<ns0:message>

<Students><Student_Name>Srinivas</Student_Name><Student_FullName>Srinivas_Kumar</Student_FullName><DOB>1992-09-25</DOB><FlatNo>#04, 8th main</FlatNo><Locality>Gandhi Road</Locality></Students>

</ns0:message>

please help me in this.

Accepted Solutions (0)

Answers (2)

Answers (2)

former_member183816
Active Participant
0 Kudos

Use CDATA and form your xml like this, This way, you don't have to replace anything in your original xml.

<?xml version="1.0" encoding="UTF-8"?>

<message>

<![CDATA[<Students><Student_Name>Srinivas</Student_Name><Student_FullName>Srinivas_Kumar</Student_FullName><DOB>1992-09-25</DOB><FlatNo>#04, 8th main</FlatNo><Locality>Gandhi Road</Locality></Students> ]]>

</message>

Tell your receiver system that you are sending actual xml within message tag as CDATA. They should be able to extract it correctly in this format.

You can refer java codes mentioned above to form it.

former_member182412
Active Contributor
0 Kudos

Hi King,

Do the similar kind of mapping.

Regards,

Praveen.

0 Kudos

HI Praveen,

i need this logic as a java code sir. i need to use this in a java mapping.

when i convert an input xml file as a string and write that string to output file in xml format i am facing a issue like that string was always taking as a xml code but not as a plain string.

can you help me writing the same logic as java code.

nitindeshpande
Active Contributor
0 Kudos

Hello,

Why you want to go for java mapping, when you can fulfill it easily using graphical mapping? Any specific reason you want to go for java mapping instead of graphical?

Regards,

Nitin

0 Kudos

HI Nitin,

I have to do this as a java mapping & i have someother logics which needs to be implemented later in this code.

and also i have to code dynamically & this should not stick to one file.

nitindeshpande
Active Contributor
0 Kudos

Hello,

Ok. You can use the below code to convert your xml data into string and replace the actual XML declaration with the blank string. After this conversion you have the whole XML data converted into String.

Header 1

public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput) throws StreamTransformationException {

         try {

             InputStream inputstream = transformationInput.getInputPayload().getInputStream();

             OutputStream outputstream = transformationOutput.getOutputPayload().getOutputStream();

             // a) Copy Input content to String

             byte[] b = new byte[inputstream.available()];

             inputstream.read(b);

             String inputContent = new String(b);

            

             inputContent = inputContent.replaceAll("<?xml version= \"1.0\" encoding= \"UTF-8\" ?>", "");

          

             outputstream.write(inputContent.getBytes());

         } catch (Exception exception) {

             getTrace().addDebugMessage(exception.getMessage());

             throw new StreamTransformationException(exception.toString());

         }

     }

Regards,

Nitin

0 Kudos

Hi nitin,

Earlier I was done upto string conversion and inserted that string in the output xml file but it always taking that string as a xml code but not as a plain string.

see the code below(just see the logic later i can convert this code into PI compatible)

public static void main(String[] args)throws IOException

    {

  FileInputStream fin = new FileInputStream("path");

  FileOutputStream fout = new FileOutputStream("path");

  BufferedReader br = new BufferedReader(new InputStreamReader(fin));

  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout));

  br.readLine();

  String initialtag = "some code";

  String endtag = "some code";

  String line ;

  System.out.println("String Conversion Started");

  bw.write(initialtag);

    while((line = br.readLine()) != null)

        {

  //line.replaceAll("<","&lt");

    //line.replaceAll(">","&gt");

        bw.append(line);

    }

        bw.write(endtag);      

  bw.close();

  System.out.println("String Conversion Completed");

    }

another logic (line.replaceall.....) i tried this too but this didnt work

nitindeshpande
Active Contributor
0 Kudos

Hello,

Can you try with the code provided by me? Any data coming from PI must be 1st converted into bytes before converting it into String.

The above code should work. I have already tried it.

Additionally you can concat the String with the <Messages> </Messages> tag to get your desired output. Once concatenated, convert back the output to Outputstream.

Regards,

Nitin

markangelo_dihiansan
Active Contributor
0 Kudos

Hi,

Can you try this code:


import com.sap.aii.mapping.api.AbstractTransformation;

import com.sap.aii.mapping.api.StreamTransformationException;

import com.sap.aii.mapping.api.TransformationInput;

import com.sap.aii.mapping.api.TransformationOutput;

import com.sap.aii.utilxi.core.io.IOUtil; //if this is no longer available for your PI system, use Apache Commons IOUtils

public class test extends AbstractTransformation{

     public void transform(TransformationInput input, TransformationOutput output) throws StreamTransformationException {

          try{

               StringBuffer outputpayload = new StringBuffer("");

               InputStream inputStream = input.getInputPayload().getInputStream();

               String output = IOUtil.copyToString(inputStream, "UTF-8");

               inputStream.close();

               outputpayload.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

               outputpayload.append("<ns0:message xmlns:ns0=\"testnamespace\">");

               outputpayload.append(output.substring(output.indexOf("?>")+2));

               outputpayload.append("</ns0:message>");

               output.getOutputPayload().getOutputStream().write(outputpayload.toString().getBytes("UTF-8"));

          }

          catch(Exception ie){

               ie.getMessage();

          }

     }

}

Output:


<?xml version="1.0" encoding="UTF-8"?>

<ns0:message xmlns:ns0="testnamespace">

   <Students>

      <Student_Name>Srinivas</Student_Name>

      <Student_FullName>Srinivas_Kumar</Student_FullName>

      <DOB>1992-09-25</DOB>

      <FlatNo>#04, 8th main</FlatNo>

      <Locality>Gandhi Road</Locality>

   </Students>

</ns0:message>

Regards,

Mark

former_member182412
Active Contributor
0 Kudos

Hi King,

You can use below java mapping.


import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import com.sap.aii.mapping.api.AbstractTransformation;

import com.sap.aii.mapping.api.StreamTransformationException;

import com.sap.aii.mapping.api.TransformationInput;

import com.sap.aii.mapping.api.TransformationOutput;

public class XMLToStringJavaMap extends AbstractTransformation {

  @Override

  public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput)

  throws StreamTransformationException {

  try {

  InputStream inputStream = transformationInput.getInputPayload().getInputStream();

  byte[] buf = new byte[inputStream.available()];

  inputStream.read(buf);

  String inputPayloadString = new String(buf, "utf-8");

  inputPayloadString = inputPayloadString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  factory.setIgnoringElementContentWhitespace(true);

  DocumentBuilder builder = factory.newDocumentBuilder();

  Document outputDoc = builder.newDocument();

  Element outMsgType = outputDoc.createElement("MT_XMLToString");

  outMsgType.setAttribute("ns0", "urn:pi:javamapping:prototype");

  outputDoc.appendChild(outMsgType);

  Element fileNameElement = outputDoc.createElement("message");

  fileNameElement.setTextContent(inputPayloadString);

  outMsgType.appendChild(fileNameElement);

  Transformer transformer = TransformerFactory.newInstance().newTransformer();

  transformer.setOutputProperty("indent", "yes");

  transformer.transform(new DOMSource(outputDoc), new StreamResult(transformationOutput.getOutputPayload()

  .getOutputStream()));

  } catch (Exception e) {

  getTrace().addDebugMessage(e.getMessage());

  throw new StreamTransformationException(e.getMessage());

  }

  }

}

Regards,

Praveen.

0 Kudos

Hi Praveen,

can this be converted into compatibility of Net Weaver Developer Studio(NWDS).

because i will have to try with a input file and a output destination before importing to PI.

0 Kudos

Hi Mark,

can this be converted into compatibility of Net Weaver Developer Studio(NWDS).

because i will have to try with a input file and a output destination before importing to PI.

former_member182412
Active Contributor
0 Kudos

Hi King,

You can test the java mapping in NWDS using this blog

Regards,

Praveen.

markangelo_dihiansan
Active Contributor
0 Kudos

Hi King,

Yes of course. Just replace the Transformation input/output with FileInputStream/FileOutputStream.

Regards,

Mark

0 Kudos

Hi Mark,

This code is not working.

it is converting to string and appending to output file but the string in the output file is considering as xml code but not as string.

used code is


import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import com.sap.aii.utilxi.core.io.IOUtil;

//if this is no longer available for your PI system, use Apache Commons IOUtils 

public class XmltoString { 

  public static void main(String[] args) { 

          try{ 

               StringBuffer outputpayload = new StringBuffer(""); 

               InputStream inputStream = new FileInputStream("C:/Users/xsmuthyaya/Desktop/Test/input.xml");

               OutputStream outputStream = new FileOutputStream("C:/Users/xsmuthyaya/Desktop/Test/op2string.xml");

               String output = IOUtil.copyToString(inputStream, "UTF-8"); 

               inputStream.close(); 

               outputpayload.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 

               outputpayload.append("<ns0:message xmlns:ns0=\"testnamespace\">"); 

               outputpayload.append(output.substring(output.indexOf("?>")+2)); 

               outputpayload.append("</ns0:message>"); 

               outputStream.write(outputpayload.toString().getBytes("UTF-8")); 

          } 

          catch(Exception ie){ 

               ie.getMessage(); 

          } 

     } 

}

output should be like

<?xml version="1.0" encoding="UTF-8"?><ns0:message xmlns:ns0="testnamespace">

<Students><Student_Name>Srinivas</Student_Name><Student_FullName>Srinivas_Kumar</Student_FullName><DOB>1992-09-25</DOB><FlatNo>#04, 8th main</FlatNo><Locality>Gandhi Road</Locality></Students>

</ns0:message>

all the underlined code should be shown as a string but not as a xml code.

0 Kudos

Hi Praveen,

i am bit confused with that blog.

can you please convert that code in to input/outputfilestream compatible instead of transformationinput/output? that would be helpful.

output should be like

<?xml version="1.0" encoding="UTF-8"?><ns0:message xmlns:ns0="testnamespace">

<Students><Student_Name>Srinivas</Student_Name><Student_FullName>Srinivas_Kumar</Student_FullName><DOB>1992-09-25</DOB><FlatNo>#04, 8th main</FlatNo><Locality>Gandhi Road</Locality></Students>

</ns0:message>

all the underlined code should be shown as a string but not as a xml code.

former_member182412
Active Contributor
0 Kudos

Hi King,


import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import com.sap.aii.mapping.api.AbstractTransformation;

import com.sap.aii.mapping.api.StreamTransformationException;

import com.sap.aii.mapping.api.TransformationInput;

import com.sap.aii.mapping.api.TransformationOutput;

public class XMLToStringJavaMap extends AbstractTransformation {

  public static void main(String[] args) throws FileNotFoundException, StreamTransformationException {

  FileInputStream fis = new FileInputStream("StudentsInput.xml");

  XMLToStringJavaMap javaMap = new XMLToStringJavaMap();

  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  javaMap.transform(fis, baos);

  System.out.println(new String(baos.toByteArray()));

  }

  @Override

  public void transform(TransformationInput transformationInput, TransformationOutput transformationOutput)

  throws StreamTransformationException {

  transform(transformationInput.getInputPayload().getInputStream(), transformationOutput.getOutputPayload()

  .getOutputStream());

  }

  public void transform(InputStream inputStream, OutputStream outputStream) throws StreamTransformationException {

  try {

  byte[] buf = new byte[inputStream.available()];

  inputStream.read(buf);

  String inputPayloadString = new String(buf, "utf-8");

  inputPayloadString = inputPayloadString.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  factory.setIgnoringElementContentWhitespace(true);

  DocumentBuilder builder = factory.newDocumentBuilder();

  Document outputDoc = builder.newDocument();

  Element outMsgType = outputDoc.createElement("MT_XMLToString");

  outMsgType.setAttribute("ns0", "urn:pi:javamapping:prototype");

  outputDoc.appendChild(outMsgType);

  Element fileNameElement = outputDoc.createElement("message");

  fileNameElement.setTextContent(inputPayloadString);

  outMsgType.appendChild(fileNameElement);

  Transformer transformer = TransformerFactory.newInstance().newTransformer();

  transformer.setOutputProperty("indent", "yes");

  transformer.transform(new DOMSource(outputDoc), new StreamResult(outputStream));

  } catch (Exception e) {

  getTrace().addDebugMessage(e.getMessage());

  throw new StreamTransformationException(e.getMessage());

  }

  }

}

Output: It is just display in console.

If you open in any xml editor it will look like below.

Regards,

Praveen.