-1

Suppose I have xml like this:

<A>
 <B>
  <users>
   <user>
    <Name>User1</Name>
   </user>
   <user>
    <Name>User2</Name>
   </user>
</users>
 </B>
</A>

I want to deserialize only the users node.

Here is what I'm doing.

XmlSerializer serializer = new XmlSerializer(typeof(List<User>), new XmlRootAttribute("users"));

StringReader sr = new StringReader(xmlstring);
using (var reader = XmlReader.Create(sr))
{
    var resultda = serializer.Deserialize(reader);
}

But it throws an exception <A xmlns=''> was not expected.

Andrej Kovalksy
  • 225
  • 1
  • 3
  • 13
  • Possible duplicate of [Deserialize a portion of xml into classes](http://stackoverflow.com/questions/22083548/deserialize-a-portion-of-xml-into-classes) – Erik Philips Nov 19 '15 at 15:13

2 Answers2

1

You should define specific serialization parameters for your User class first:

[XmlRoot("users")]
[System.Xml.Serialization.XmlType(TypeName="user")]
public class User
{
    public string Name { get; set; }
}

And since you want to read the "users" node, you should first get that node and deserialize that node:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlstring);
XmlNode usersNode = xmlDocument.SelectSingleNode("A/B/users");

StringReader sr = new StringReader(usersNode.OuterXml);
using (var reader = XmlReader.Create(sr))
{
    List<User> resultda = (List<User>)serializer.Deserialize(reader);
    Console.WriteLine(resultda.Count);
}

NOTE: It is always helpful to do it backwards if you have any problems with deserialization, meaning, just populate the object and serialize it, try/fail and finally get to your expected xml format

        List<User> users = new List<User>();
        users.Add(new User { Name = "User 1" });
        users.Add(new User { Name = "User 2" });
        new XmlSerializer(typeof(List<User>), new XmlRootAttribute("users")).Serialize(Console.OpenStandardOutput(), users);
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
0
[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

this should be in the class you re deserializing to.


{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Community
  • 1
  • 1
Slasko
  • 407
  • 2
  • 8