XmlSerializer在Root上反序列化多个对象的数组/列表

Bri*_*vez 0 c# serialization xml-serialization xmlroot

我正在尝试反序列化以下XML输出:

<?xml version="1.0" encoding="ISO-8859-1"?>
<Foo>
   <Val>Data1</Val>
</Foo>
<Foo>
   <Val>Data2</Val>
</Foo>
Run Code Online (Sandbox Code Playgroud)

(这是从硬件设备输出,不能更改)

我有一个XML类型定义为:

    [XmlType(AnonymousType=true, Namespace="")]
    public class Foo
    {
        public string Val { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我试图通过创建一个序列化器来反序列化这个数组:

  var s = new XmlSerializer(typeof(Foo[]));
  //or
  var s = new XmlSerializer(typeof(List<Foo>);
Run Code Online (Sandbox Code Playgroud)

但每次调用s.Deserialize()都会导致InvalidOperaitonException:

 System.InvalidOperationException: <Foo xmlns=''> was not expected.
Run Code Online (Sandbox Code Playgroud)

注意

 var s = new XmlSerializer(typeof(Foo));
 // Only deseralizes the first Foo (Data1).
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Adr*_*der 8

我认为问题在于你提供的xml.

测试应用说

List<Foo> list = new List<Foo> {new Foo {Val = "Data1"}, new Foo {Val = "Data2"}};
var s = new XmlSerializer(typeof(List<Foo>));
StringBuilder sb = new StringBuilder();
XmlWriter wr = XmlWriter.Create(sb);
s.Serialize(wr, list);

string ss = sb.ToString();

var s2 = new XmlSerializer(typeof(List<Foo>));
StringReader sr = new StringReader(ss);
List<Foo> returnList = (List<Foo>)s2.Deserialize(sr);
Run Code Online (Sandbox Code Playgroud)

而XML应该是

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfFoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Foo>
        <Val>Data1</Val>
    </Foo>
    <Foo>
        <Val>Data2</Val>
    </Foo>
</ArrayOfFoo>
Run Code Online (Sandbox Code Playgroud)

如果你可以删除初始线

<?xml version="1.0" encoding="ISO-8859-1"?>
Run Code Online (Sandbox Code Playgroud)

并将字符串缩小为

string s = "<ArrayOfFoo><Foo>   <Val>Data1</Val></Foo><Foo>   <Val>Data2</Val></Foo></ArrayOfFoo>";
var s2 = new XmlSerializer(typeof(List<Foo>));
StringReader sr = new StringReader(s);
List<Foo> list = (List<Foo>)s2.Deserialize(sr);
Run Code Online (Sandbox Code Playgroud)

那可能有用.


cjk*_*cjk 7

那是无效的Xml.需要有一个核心根元素才能正常工作.