Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

c# - Deserializing XML with namespace and multiple nested elements

I am trying to deserialize the following xml

<?xml version="1.0" encoding="utf-8"?>
<ns2:myroot xmlns:ns2="http://jeson.com/">
  <item>
    <name>uno</name>
    <price>1.25</price>
  </item>
  <item>
    <name>dos</name>
    <price>2.30</price>
  </item>
</ns2:myroot>

with these classes

public class item
{
    [XmlElement(Namespace="")]
    public string name { get; set; }

    [XmlElement(Namespace = "")]
    public double price { get; set; }
}

[XmlRoot("myroot", Namespace="http://jeson.com/")]  //This was http://jeson.com, no slash at the end.
public class myrootNS
{
    [XmlElement(Namespace = "")]
    public item[] item { get; set; }
}

using this method

XmlSerializer serializer = new XmlSerializer(typeof(T), "http://jeson.com/");
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml))
{
    using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
    {
        return (T)serializer.Deserialize(xmlReader);
    }
}

but somehow I keep getting this error.

System.InvalidOperationException: There is an error in XML document (2, 2). ---> 
System.InvalidOperationException: <myroot xmlns='http://jeson.com/'> was not expected.

What is the correct way of doing it ? The method works for deserializing without the namespace.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the namespace of myrootNS class is incorrect because it doesn't match the expected namespace in the XML.

[XmlRoot("myroot", Namespace = "http://jeson.com/")]
public class myrootNS
{
    [XmlElement(Namespace = "")]
    public item[] item { get; set; }
}

Notice that the Namespace property value has a trailing /. This is my deserialize method:

static T Deserialize<T>(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    XmlReaderSettings settings = new XmlReaderSettings();
    using (StringReader textReader = new StringReader(xml))
    {
        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
        {
            return (T)serializer.Deserialize(xmlReader);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...