1

I need to deserialize plain xml, without namespace and root element, for example:

    <element name="1">
       <subelement1>2</subelement/>
    </element>
    <element name="2">
     <subelement1>3</subelement/>
    </element>

How can I do this using XmlSerializer? I have XmlDataset, which was generated by xsd.exe. But when i use code I see InvalidOperationException with message "< xmlns=''> not expected"

IComparable
  • 71
  • 1
  • 1
  • 10
  • 1
    That is simply not a valid xml document (multiple root nodes are not legal); `XmlSerializer` will not like that. The rest, however, is trivial and should just work fine with `[XmlRoot("element")]` – Marc Gravell Oct 24 '14 at 17:36
  • I agree. You need to have valid XML if you want the XMLSerializer to work with it. Just create a new XML document with a root node and add that fragment inside the root node. Now it is valid XML. – DVK Oct 24 '14 at 18:00

2 Answers2

1

Like below. Key points:

  • you need to control the reader manually to set the conformance level to "fragment", to allow multiple root nodes
  • you need to obtain a sub-tree reader per root node for XmlSerializer to work against

Code:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("element")]
public class MyElement
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlElement("subelement1")]
    public string Value { get; set; }

}
public static class Program
{
    static void Main()
    {
        var xml = @"
<element name=""1"">
    <subelement1>2</subelement1>
</element>
<element name=""2"">
    <subelement1>3</subelement1>
</element>";
        var ser = new XmlSerializer(typeof(MyElement));
        using (var sr = new StringReader(xml))
        using (var xr = XmlReader.Create(sr, new XmlReaderSettings
        {
            IgnoreWhitespace = true,
            ConformanceLevel = System.Xml.ConformanceLevel.Fragment
        }))
        {
            while (xr.MoveToContent() == XmlNodeType.Element)
            {
                using (var subtree = xr.ReadSubtree())
                {
                    var obj = (MyElement)ser.Deserialize(subtree);
                    Console.WriteLine("{0}: {1}",
                        obj.Name, obj.Value);
                }
                xr.Read();
            }
        }
    }

}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

This SO question may be helpful. It involves using dynamic as opposed to the xsd you mentioned.

As for the InvalidOperationException issue, can you post a simple, complete example of your XML that produces the error? It will help in identifying the problem.

Community
  • 1
  • 1
Nx'
  • 26
  • 3