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
214 views
in Technique[技术] by (71.8m points)

c# - Deserializing XML from String

I'm trying to convert the result I get from my web service as a string and convert it to an object.

This is the string I'm getting from my service:

<StatusDocumentItem><DataUrl/><LastUpdated>2013-01-31T15:28:13.2847259Z</LastUpdated><Message>The processing of this task has started</Message><State>1</State><StateName>Started</StateName></StatusDocumentItem>

So I have a class for this as:

[XmlRoot]
public class StatusDocumentItem
{
    [XmlElement]
    public string DataUrl;
    [XmlElement]
    public string LastUpdated;
    [XmlElement]
    public string Message;
    [XmlElement]
    public int State;
    [XmlElement]
    public string StateName;
}

And this is how I'm trying to get that string as an object of type StatusDocumentItem with XMLDeserializer (NB. operationXML contains the string):

string operationXML = webRequest.getJSON(args[1], args[2], pollURL);
var serializer = new XmlSerializer(typeof(StatusDocumentItem));
StatusDocumentItem result;

using (TextReader reader = new StringReader(operationXML))
{
    result = (StatusDocumentItem)serializer.Deserialize(reader);
}

Console.WriteLine(result.Message);

But my result object is always empty. What am I doing wrong?

Update. The value I get from my operationXML is like this and has an unnecessary xmlns attribute that is blocking my deserialization. Without that attribute, everything is working fine. Here is how it looks like:

"<StatusDocumentItem xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><DataUrl/><LastUpdated>2013-02-01T12:35:29.9517061Z</LastUpdated><Message>Job put in queue</Message><State>0</State><StateName>Waiting to be processed</StateName></StatusDocumentItem>"
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try this:

string xml = "<StatusDocumentItem xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><DataUrl/><LastUpdated>2013-02-01T12:35:29.9517061Z</LastUpdated><Message>Job put in queue</Message><State>0</State><StateName>Waiting to be processed</StateName></StatusDocumentItem>";
var serializer = new XmlSerializer(typeof(StatusDocumentItem));
StatusDocumentItem result;

using (TextReader reader = new StringReader(xml))
{
    result = (StatusDocumentItem)serializer.Deserialize(reader);
}

Console.WriteLine(result.Message);
Console.ReadKey();

Does it show "Job put in queue"?


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

1.4m articles

1.4m replys

5 comments

57.0k users

...