Binary to xml java

Как вы встраиваете двоичные данные в XML?

У меня есть два приложения, написанные на Java, которые обмениваются данными друг с другом с помощью XML-сообщений по сети. Я использую SAX-парсер на принимающей стороне, чтобы получить данные обратно из сообщений. Одним из требований является встраивание двоичных данных в XML-сообщение, но SAX это не нравится. Кто-нибудь знает, как это сделать? UPDATE: я получил эту работу с классом Base64 из apache commons codec library, если кто-то еще пытается что-то подобное.

13 ответов

Вы можете закодировать двоичные данные с помощью base64 и поместить его в элемент Base64; ниже статья является довольно хорошей по этому вопросу.

Будьте осторожны, некоторые брандмауэры (https-соединения) иногда блокируются при наличии символа «=». (Многие кодировки строки приводят к чему-то вроде этого «kdiLKjdfdilfse =»)

XML настолько универсален.

XML похож на насилие. Если это не решит вашу проблему, вы не используете его достаточно.

BTW: Base64 + CDATA, вероятно, лучшее решение

(EDIT2:
Кто бы ни передумал, пожалуйста, также поднимите настоящий ответ. Мы не хотим, чтобы какая-нибудь бедная душа приходила сюда и действительно применяла мой метод, потому что она была наивысшей оценкой на SO, верно?)

Я только что повторил эту цитату своему другу, и после того, как он засмеялся, он сказал: «И больно, если тебя направят» 🙂

Читайте также:  Javascript onclick window open location

Да ладно тебе, юмористические мерзавцы . загорелись. Это был ранний ответ, прежде чем мы все изучили ТАК этикет . 🙂

Это не что иное, как позорное использование XML, если вы серьезно. А если нет, то как об этом узнают начинающие, которые не пишут «высокий уровень — думаю — низкий уровень»?

Джереми . для молодого 23-летнего парня вы ужасно серьезны / буквальны . вы явно недостаточно проработали в отрасли, чтобы понять, почему это забавный ответ с предостерегающим рассказом для смелых между строк ,

Куда испарилось наше чувство юмора? Это был закрытый бета-дневный вопрос . тогда была некоторая свобода действий. Пожалуйста, вставьте модуль юмора.

Я бы предположил, что они будут знать, 1) насколько этот ответ отличается от большого зеленого выше с удвоенным числом голосов, и 2) читая остальную часть темы, где другие указывают, насколько забавна эта шутка.

@ Майк — ты бы так подумал . ТАК быстро становится питательной средой для молодых эгоманических юмористических педантов.

Я думаю, что это смешно. Но да, еще раз, использование фактического типа данных base64 — путь. CData слишком общий.

+1 за установку зеркала для всех тех консультантов, которые считают XML = золотой молоток, смеется. Кстати, я люблю XML, но только если используется правильно.

Я не думаю, что это достаточно наглядно — возможно, следует использовать «BINARYDIGIT», а не «BIT»? 😉

Может быть, edit2 должен быть отказ от ответственности, вверху, голова. РЕДАКТИРОВАТЬ понизил исключительно для того, чтобы получить его еще дальше от самого высокого рейтинга.

Я думаю, что очень интересно, что после всех этих лет этот ответ на шутку все еще имеет большинство голосов. Возможно, это показывает, что существует реальная разница в значениях пользователей SO, которые голосуют за ответы, и модераторов, которые в наши дни подавляют малейший намек на легкомыслие или отсутствие серьезности.

Base64 действительно правильный ответ, но CDATA не является, в основном говоря: «это может быть что угодно», однако оно должно не быть чем угодно, оно должно быть двоичными данными, закодированными в Base64. XML Schema определяет Base 64 двоичный как примитивный тип данных, который вы можете использовать в своем xsd.

Дополнительная точка для упоминания типа данных xs:base64Binary , который является правильным типом для использования.

У меня была эта проблема только на прошлой неделе. Мне пришлось сериализовать PDF файл и отправить его внутри XML файла на сервер.

Если вы используете .NET, вы можете преобразовать двоичный файл непосредственно в строку base64 и вставить его внутри XML-элемента.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName)); 

Или существует метод, встроенный прямо в объект XmlWriter. В моем конкретном случае мне пришлось включить пространство имен типов данных Microsoft:

StringBuilder sb = new StringBuilder(); System.Xml.XmlWriter xw = XmlWriter.Create(sb); xw.WriteStartElement("doc"); xw.WriteStartElement("serialized_binary"); xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64"); byte[] b = File.ReadAllBytes(fileName); xw.WriteBase64(b, 0, b.Length); xw.WriteEndElement(); xw.WriteEndElement(); string abc = sb.ToString(); 

Строка abc выглядит примерно так:

   JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw. (plus lots more)  

Источник

How do you embed binary data in xml

Solution 1: Why would you want to embed binary data into XML? There are lots of better ways than trying to stuff binary data into XML.

How do you embed binary data in XML?

You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.

Handling Binary Data in XML Documents

XML is like violence — If it doesn’t solve your problem, you’re not using enough of it.

BTW: Base64 + CDATA is probably the best solution

(EDIT2:
Whoever upmods me, please also upmod the real answer. We don’t want any poor soul to come here and actually implement my method because it was the highest ranked on SO, right?)

Base64 is indeed the right answer but CDATA is not, that’s basically saying: «this could be anything», however it must not be just anything, it has to be Base64 encoded binary data. XML Schema defines Base 64 binary as a primitive datatype which you can use in your xsd.

Inserting into binary xml from blob, below are the few lines from the oracle documents » Use insert select as syntax to move the data from scott.tb blob into scott.po_bin XMLType table stored as Binary XML SQL> insert into po_bin …

How to embed binary data in XML using XML Builder?

I think you need to do something with the binary stream, because it has some invalid characters for XML.

Here is a document about handle binary data in xml, it’s language independent, just xml.

In this case, I think the easiest way to handle your attachment is using base64. If @invoice.attachment is the binary string, use the code below, if not, get it:

xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8" xml.invoice(:invoice_no => @invoice.number) do xml.pdf Base64.encode64(@invoice.attachment) end 

When you read the xml, decode the string with base64 format and get the binary string.

How do I embed an uploaded binary files (ASCII-8BIT) in, First, you cannot embed a binary file in an XML document without some sort of conversion to text. At least the PDF document and the PNG image need to be encoded somehow — probably Base64 — before you start trying to treat their contents as strings of characters instead of sequences of bytes.

Rest + xop / binary data embedded in xml response

Why would you want to embed binary data into XML? There are plenty of ways to associate binary resources to their corresponding metadata without trying to stuff it into a single representation.

You are defeating one of the primary benefits of REST HTTP. The ability to handle multiple different media-types based on the requirements is one of the reasons using REST over HTTP can be more effective than SOAP.

Consider retrieving an XML representation of the metadata that contains a link to the binary resource as Atom does. If you want to retrieve the binary first, then consider Link Headers to point to the metadata. There are lots of better ways than trying to stuff binary data into XML.

I’m not sure about Jersey, but CXF has support for XOP. Perhaps you can take inspiration from there?

How do you convert binary data to Strings and back in, See this question, How do you embed binary data in XML? Instead of converting the byte [] into String then pushing into XML somewhere, convert the byte [] to a String via BASE64 encoding (some XML libraries have a type to do this for you). The BASE64 decode once you get the String back from XML. Use …

Practical way to encode binary data in XML files meant for editing by hand?

If the blobs can be reproduced easily from the original file, you can simply refer to them. Something like

 # in another file: 1 1000 2000 

As the original files will be deleted (see comment), the above can’t be used as is.

 # Another file. Depending on space/time requirements, you may either # not compress anything, compress the whole file, or compress each blob. [blob 1][blob 2][blob 3] 

If you absolutely require single-file output, you can also embed the second file in the XML (with encoding + checksum), but it’s not much improvement over your original idea.

Sql server — How can I insert binary file data into a binary, If you mean using a literal, you simply have to create a binary string: insert into Files (FileId, FileData) values (1, 0x010203040506) And you will have a record with a six byte value for the FileData field.

Источник

Serialize Binary data to XML

The following example shows serializing a POJO with binary data to an XML. The POJO should have a no-arg default constructor and @XmlRootElement annotation at class level.

package com.bethecoder.tutorials.jaxb.common;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BinaryData < private byte [] data;

public byte [] getData () <
return data;
>

public void setData ( byte [] data ) <
this .data = data;
>

>

package com.bethecoder.tutorials.jaxb.tests;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.bethecoder.tutorials.jaxb.common.BinaryData;

public class BinaryToXML < public static void main ( String [] args ) throws JAXBException < BinaryData binaryData = new BinaryData () ;
binaryData.setData ( «BE THE CODER» .getBytes ()) ; //encoded in xs:base64Binary by default

/**
* Create JAXB Context from the classes to be serialized
*/
StringWriter output = new StringWriter () ;
JAXBContext context = JAXBContext.newInstance ( BinaryData. class ) ;
Marshaller m = context.createMarshaller () ;
m.setProperty ( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ) ;
m.marshal ( binaryData, output ) ;
System.out.println ( output.toString ()) ;

/**
* Unmarshall
*/
Unmarshaller um = context.createUnmarshaller () ;
StringReader sr = new StringReader ( output.toString ()) ;
binaryData = ( BinaryData ) um.unmarshal ( sr ) ;
System.out.println ( «Data decoded : » + new String ( binaryData.getData ())) ;

>
>

Источник

Оцените статью