开发者

c# byte array xml serialization

开发者 https://www.devze.com 2023-04-01 07:41 出处:网络
I got a byte array public byte[] values; I fill it with data new byte[64]; I serialize it and I get the following XML part:

I got a byte array

public byte[] values;

I fill it with data

new byte[64];

I serialize it and I get the following XML part:

<values>
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
</values>

I found the following solution here in SO:

[XmlElement("values", DataType = "hexBinary")]
        public byte[] values;

Now I get the same XML as above just with "0" instead of "A".

When I serialize e.g. a Int16/Int32/sbyte array. I get something like this in XML:

<values>0</values>
<values>0</values>
<values>0</values>

In a vertical arrangement.

Now my questi开发者_开发知识库on: Is it possible to get a byte array also in a vertical arrangement? Like:

    <values>00</values>
    <values>00</values>
    <values>00</values>

Mark


public class Test
{
    public List<byte> Bytes { get; set; }
}

var xml = new XmlSerializer(typeof(Test));
xml.Serialize(File.Open("test.xml",FileMode.OpenOrCreate),
              new Test
              {
                  Bytes = new List<byte> {0,1,2,3,4,5,6,7}
              });

results in a xml file like:

<?xml version="1.0"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Bytes>
    <unsignedByte>0</unsignedByte>
    <unsignedByte>1</unsignedByte>
    <unsignedByte>2</unsignedByte>
    <unsignedByte>3</unsignedByte>
    <unsignedByte>4</unsignedByte>
    <unsignedByte>5</unsignedByte>
    <unsignedByte>6</unsignedByte>
    <unsignedByte>7</unsignedByte>
  </Bytes> 
</Test>


I guess you'd have to explicitly go create a new XML element for each byte in the array. You might as well use a List<byte> or Array<byte> for doing that, instead of a raw array.

As the_ajp said in the comment.

If you're getting an error trying to serialize the list, you've done something wrong. Post the code, perhaps we can help.

0

精彩评论

暂无评论...
验证码 换一张
取 消