Convert XML data to byte array...

Hello All,
In my application, i have an XML file and the corresponding XSD file. This XML file is having some date, which i want to convert into an byte[] and then save it in a file. 
How i can convert the XML data in the byte[]? Here as an example of the xml file and the byte[] data which i want to save in a file.
<?xml version="1.0" encoding="utf-8"?>
<HeadersInfo>
<header>
<id>0</id>
<Name>H1</Name>
</header>
<header>
<id>1</id>
<Name>H2</Name>
</header>
</HeasersInfo>
In the above example 'id' field is of type 'uint' and 'name' field is of type 'string' with max length of '5'. So in this case my byte array should be as shown below:
00 00 00 01 48 31 00 00 00
00 00 00 02 48 32 00 00 00
Here underlines values are for the 'id' parameter where as values in bold are for 'Name' parameter for all the header values in sequence. Name parameter is null (0x00) padded.
Thanks in advance,
IamHuM

Hi,
the following example extract the id, name values using LINQ To Xml and writes it to a memory stream using a binary writer and returns the result as a byte array:
internal static byte[] GetXmlAsByteArray()
var document = XDocument.Parse("<HeadersInfo>"
+ " <header><id>1</id><Name>H1</Name></header>"
+ " <header><id>2</id><Name>H2</Name></header>"
// additional testing
+ " <header><id>32767</id><Name>H1234</Name></header>"
+ " <header><id>305419896</id><Name>H56789</Name></header>"
+ "</HeadersInfo>");
const int NameLength = 5; // Max length for a name
byte[] zeroBytes = new byte[NameLength]; // Helper to fill name
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
// write each header
foreach (var header in document.Root.Elements("header"))
int id = (int)header.Element("id");
string name = (string)header.Element("Name");
byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(name);
Console.WriteLine("id: {0}, Name: {1}", id, name);
// Write id
writer.Write(GetUIntBytes((uint)id));
// Write name NameLength (5) max, otherwise padded
if (nameBytes.Length > NameLength)
writer.Write(nameBytes, 0, NameLength);
else
writer.Write(nameBytes, 0, nameBytes.Length);
if (nameBytes.Length < NameLength)
writer.Write(zeroBytes, 0, NameLength - nameBytes.Length);
byte[] result = ms.ToArray();
// dump array
foreach (var value in result)
Console.Write("{0:X2} ", value);
Console.WriteLine();
return result;
public static byte[] GetUIntBytes(uint value)
if (BitConverter.IsLittleEndian)
// swap bytes
value = ((value & 0x00ff) << 24)
| ((value & 0xff00) << 8)
| ((value & 0x00ff0000) >> 8)
| ((value & 0xff000000) >> 24);
return BitConverter.GetBytes(value);
For a general purpose solution you should create a class and split the example into separate methods to extract the data and write the values (integers, strings).
Regards, Elmar

Similar Messages

  • Need to have  'variable name' node in the converted XML data.

    i am converting the abap data to xml using cl_xml_document. in the converted xml data, i need to have one more node. in the below example, i want a node  <variable name="productionOrderDetails"> to come after the Data node.
    ?xml version="1.0"?>
    <Data>
         <item>
              <DISPO>100</DISPO>
              <PLNBEZ>F126</PLNBEZ>
              <GAMNG>300.000</GAMNG>
              <ERFMG>285.000</ERFMG>
              <PRE_PROD>100.000</PRE_PROD>
              <PRE_BLOG>0.000</PRE_BLOG>
              <BLOG_MTD>144.000</BLOG_MTD>
              <BAL_PLAN>144.000</BAL_PLAN>
         </item>
    </Data>
    thanks in advance

    Hi ,
    you can use class  IF_IXML_NODE, first you need to read (go thru ) XML then need to Insert a New Node.
    ref SAP Program BCCIIXMLT1/BCCIIXMLT*
    regards
    Prabhu

  • What is the best way to convert a cluster into byte array or string

    I'm writing a program that sends UDP packets and I've defined the data I want to send via large clusters (with u8/u16/u32 numbers, u8/u16/u32 arrays, and nested clusters). Right before sending the data, I need to convert the clusters either into strings or byte arrays. The flatten to string function is almost perfect for this purpose. However, it's appending lengths to arrays and strings which renders this method useless, as far as I can tell. 
    As I have many of these clusters, I would rather not hard code the unbundle by names and converting/typecasting to byte arrays or strings for each one. 
    Is there a feature or tool I am overlooking? 
    Thank you! 

    deceased wrote:
    Flatten to string has a boolean input of "Prepend string or array size" ... The default value is true.
    That only specifies if a string or array size should be prepended if the outermost data element is a string or array. For embedded strings or arrays it has no influence. This is needed for the Unflatten to be able to reconstruct the size of the embedded strings and arrays.
    The choice to represent the "Strings" (and Arrays) in the external protocol to LabVIEW strings (and arrays) is actually a pretty bad one unless there is some other element in the cluster that does define the length of the string. An external protocol always needs some means to determine how long the embedded string or array would be in order to decode the subsequent elements that follow correctly.
    Possible choices here are therefore:
    1) some explicit length in the protocol (usually prepended to the actual string or array)
    2) a terminating NULL character for strings, (not very friendly for reliable protocol parsing)
    3) A fixed size array or string
    For number 1) and 2) you would always need to do some special processing unless the protocol happens to use explicitedly 32 bit integer length indicators directly prepended before the variable sized that.
    For number 3) the best representation in LabVIEW is actually a cluster with as many elements inside as the fixed size.
     

  • XML data into an Array

    Hey,
    I have successfully loaded an external XML data file into my
    movie. Now I would like to save the node values into an array so i
    can manipulate and call as required...Is this possible or is there
    a better way to go about this?

    Well since you have the XML object loaded, all you would need
    to do is extract the nodes and data you needed then push them onto
    the array..
    If you are not too sure how to go about this, give us the XML
    schema (xml structure) of what was loaded and what you need and we
    can shoot you some basic code to get it done.

  • Is there a tool to convert XML data model into berkeleydb automatically?

    Hi all,
    Is there already a tool which convert a xml data model definition file into C++ source code with berkeleydb as underlying db implementation?
    If there is already one, I don't need to spend the time to code it.
    Regards,
    -Bruce

    Hello,
    One suggestion is to take a look at the Berkeley DB XML documentation at:
    http://docs.oracle.com/cd/E17276_01/html/toc.htm
    and see if you find what you are looking for.
    Thanks,
    Sandra

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • How to convert XML data into binary data (opaque data)

    Hi,
    I am trying to develop a process that delivers files after reading data from a database.
    However, it is required not to deliver the data immediately. We want to perform some checks before the files get written.
    So the way we want to design this is,
    1. Read data from database (or any other input). The data is in XML format (this is a requirement, as in general, we have xml data)
    2. This data is written, opaquely, to a JMS queue that can store binary data, along with what is the filename of the file that would be written (filename is passed using JMS Headers)
    3. When required, another process reads the JMS queue's binary data, and dumps into a file
    The reason I want to use opaque data while inserting in the JMS queue is, that enables me to develop a single process in Step 3 that can write any file, irrespective of the format.
    My questions are
    1. How to convert the xml data to opaque data. In BPEL I may use a embedded java, but how about ESB. Any other way....?
    2. how to pass filename to the jms queue, when payload is opaque. Can I use a header attribute...custom attributes?
    3. Which jms message type is better for this kind of requirement - SYS.AQ$_JMS_BYTES_MESSAGE or SYS.AQ$_JMS_STREAM_MESSAGE

    Ana,
    We are doing the same thing--using one variable with the schema as the source of the .xsl and assigning the resulting html to another variable--the content body of the email, in our case. I just posted how we did it here: Re: Using XSLT to generate the email HTML body
    Let me know if this helps.

  • Converting XML String to MessageElement array

    Hi,
    I am trying to call a .NET web service from my Java client. I used WSDL2Java to generate the java classes for calling the .NET web service. The generated classes to call the service expects an array of org.apache.axis.message.MessageElement objects. I have a string representing an XML document which looks like this:
    String xmlString = "<Results><Adjustments><Adjustment><RebuildAdjustmentID>16</RebuildAdjustmentID><IsBasicAdjustment>true</IsBasicAdjustment><AdjustmentType>stone/AdjustmentType><Title>External walls</Title></Adjustment></Adjustments></Results>"
    I have tried converting the string into an array of MessageElement objects by the following way:
    MessageElement[] m = new MessageElement[1];
    Document XMLDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(result2.toString())));
    m[0] = XMLDoc.getDocumentElement();
    However I keep getting the following message returned from the service:
    "Object reference not set to an instance of an object"
    I have tried a handful of ways but keep getting this same error. I have searched the web for hours looking for a solution to this problem without success so any help/ideas much appreciated,
    Thanks.
    Paul

    Any updates on this?
    I am facing a similar problem.

  • Convert float to 4 bytes array

    How can I convert float type to 4 byte array -
    not with strings but to exact binary representation.

    See the javadoc of Float.floatToIntBits. Converting an int to an array of 4 bytes is easy, so I will left it as an exercise.
    floatToIntBits
    public static int floatToIntBits(float value)Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.
    Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
    If the argument is positive infinity, the result is 0x7f800000.
    If the argument is negative infinity, the result is 0xff800000.
    If the argument is NaN, the result is 0x7fc00000.
    In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).
    Parameters:
    value - a floating-point number.
    Returns:
    the bits that represent the floating-point number.

  • Converting Image.jpg to byte array

    Hi,
    How do i convert a image (in any format like .jpeg, .bmp, gif) into a byte array
    And also vice versa, converting byte array to image format
    Thank you

    how about Class.getResourceAsStream(String name).read(byte[] b)?

  • Confusion regarding Binary data and byte arrays

    HI guys,
    I have a question...i am going to send some binary data...the format of that data is that first two bytes is the lenght of the data and then follows that data. Here i have one confusion. e.g. i want to say that the lenght of my data is 1000 bytes. How do i do it.
    coz if i do something like this.
    int k = 1000;//the length of my data
    String binaryString = Integer.toBinaryString(k);
    byte[] binaryData = binaryString.getBytes();
    and then if i say binaryData.lenght, i see a lenght of 10, as the binary string which
    is generated is -> 1111101000. i guess its obivious as this byte array is nothing but perhaps a character array with each character occupying one thread...so what exactly is the difference between byte array and binary data. and in the above said condition how do i send the binary data?
    Also adding to my confusion is the fact that i have a file which contains binary data, but that data is not 10010101 type of data...its just some absurd characters. How do we explain this.
    i would be highly grateful if you could explain me the solution to this problem.
    I am not getting as to how to go about it.
    its urgent..pls help...

    one sec..actually i dont want to 'read' the two bytes. That i know how to do? but The thing is that i want to write a binary stream. right? so in that the first two bytes should be the size of the data, followed by the data itself. So i want to write the first two bytes, which should contain the size of data (as a matter of fact i have that binary data in a byte array). But my question is , that if i say the size of data is 1000 (bytes , since, as i said i am gettting the data as a byte array), how do i write this in my binary stream as 1000 in this case would be an int. right? which is four bytes. So essentially that byte array (which contains binary data) i have to forward to somewhere, say X , but X reads binary data in the following way...it expects the first two bytes to give him info regarding the size of the data to follow and then it starts reading the data from the third byte onwards till the size of the data (which it got by reading first two bytes)...i hope i could communicate my confusion better this time

  • Converting xml data in to comma separated values in bpel

    Is there a way to covert generic xml data to comma separated value in BPEL? i have tried using createDelimitedString but no luck.
    Please guide me on this issue.
    Thanks!
    Shan
    Edited by: 876372 on Aug 3, 2011 6:58 AM

    Hi,
    Have a luk at the below link it has many examples:
    http://download.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/nfb.htm

  • Can LabVIEW convert XML data in Excel

    I am using XML files to store the data regarding my work. Now I have to display the data to the end user as a preview of the data. it could be in any readable format like HTML,MS-Excel or MS-Word.
    Can any one tell me how to convert the XML file in above format

    Hi,
    Inorder to convert a XML file to HTML you need to write an XSL script (EXtensible Style sheet Language).  This script parses the XML file with a particular schema and shows the XML file in a browser.
    Just open the XML file in Excel (2003 or above).  It automatically parses the XML schema type and provides it as worksheet!
    With regards,
    JK
    (Certified LabVIEW Developer)
    Give Kudos for Good Answers, and Mark it a solution if your problem is solved.

  • Converting XML data string in to file object to parse

    Hi
    I have XML in the form of String .. i just want to convert this string in to a file to parse.. how can i do that ..<p>
    Here is my xml string<p>
    String str = "<?xml version="1.0"?>
    <!DOCTYPE some SYSTEM "some.dtd">
    <firsttag>
         <childtag>
              <name>some name</name>
              <age>age</age>
         </childtag>
    </firsttag>";<p>
    if u have code that would be great
    Thanks in advance

    Hi
    I have XML in the form of String .. i just want to
    convert this string in to a file to parse.. how can i
    do that ..<p>
    Why not to use RandomAccessFile to write string to file(you need to do this? is i'm right?)

  • How to convert xml data into html format in bpel

    Hi ,
    Can any one tel me how to conevrt xml into html in oracle bpel.
    Does bpel support this functionality or not.
    Regards,
    Ana
    Edited by: user10181991 on Apr 5, 2009 11:16 PM

    Ana,
    We are doing the same thing--using one variable with the schema as the source of the .xsl and assigning the resulting html to another variable--the content body of the email, in our case. I just posted how we did it here: Re: Using XSLT to generate the email HTML body
    Let me know if this helps.

Maybe you are looking for

  • Cisco Jabber for Windows in Extend and Connect mode and making outbound calls

    Hi guys, I've set up Cisco Jabber for Windows to use Extend and Connect to control a remote PBX endpoint. I've configured the required CTI-RD device, remote destinations, associated the users to the line and added the devices to end-user controlled d

  • Error deploying new portal logon page

    Hi Gurus, I'm getting an error deploying my new portal logon page. I've made teh necessary changes to the portal.logon.par.bak file. I've rename it and made the necessary changes in config tool. i've created a new autoscheme_test.xml file and have as

  • Challan material is different from material document----Message no. 8I572

    Hi, I am getting the following error in subcontracting process when reconciling through J1IFQ. Challan material is different from material document----Message no. 8I572 After P.O. creation and issued the materials through 541 and created a subcontrac

  • Crop Marks have changed since CS

    Hi all, I am coming from the stone age (Illustrator CS) and the use of crop marks in CS5.5 is tripping me up.   I used to be able to drag a box around some art, change the box to crop marks and export to a .jpg that would be cropped to those marks.  

  • Oracle take very long to return.

    Hi, I have a simple select query that takes more than 20 times longer in oracle than in mysql. My table in oracle is created this way. ================================================== create table TAB (name char(15), num1 nubmer,num2 number,num3 nu