Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How can I deserialize xml with a default namespace?

I am trying to deserialize an Atom xml generated by one of the internal systems. However, when I try:

    public static MyType FromXml(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(MyType ));
        return (MyType) serializer.Deserialize(new StringReader(xml));
    }

it throws an exception on the definition of the namespace:

System.InvalidOperationException: <feed xmlns='http://www.w3.org/2005/Atom'> was not expected.

When I add the namespace to the constructor of the XmlSerializer, my object is completely empty:

    public static MyType FromXml(string xml)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(MyType ), "http://www.w3.org/2005/Atom");
        return (MyType) serializer.Deserialize(new StringReader(xml)); //this will return an empty object
    }

Any ideas how can I get it to work?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It is hard to investigate this without being able to look at how your object model ties to the xml (i.e. samples of each); however, you should be able to do something like:

[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType {...}

As a limited atom example (which works fine with some sample atom I have "to hand"):

class Program
{
    static void Main()
    {
        string xml = File.ReadAllText("feed.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(MyType));
        var obj = (MyType)serializer.Deserialize(new StringReader(xml));
    }
}
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class MyType
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("updated")]
    public DateTime Updated { get; set; }
    [XmlElement("title")]
    public string Title { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...