Xml无法正确转换为对象

时间:2018-01-31 17:45:52

标签: c# xml

我有这个XML输入:

<Response xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Status>Ok</Status></Response>

我试图通过以下方式将其转换为对象:

XmlDocument xmlNode = new XmlDocument();
xmlNode.LoadXml(responseContent);
string jsonNode = JsonConvert.SerializeXmlNode(xmlNode);
var responseModel = JsonConvert.DeserializeObject<NotificationResponse>(jsonNode); 

其中responseContent是上面的XML字符串。但是,而不是

{Status: "Ok"} 

我得到了:

{Status: null}

知道为什么以及如何纠正它?

2 个答案:

答案 0 :(得分:2)

您需要省略RootObject

XmlDocument xmlNode = new XmlDocument();
xmlNode.LoadXml("<Response xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Status>Ok</Status></Response>");
string jsonNode = JsonConvert.SerializeXmlNode(xmlNode, Formatting.Indented, true);
Console.WriteLine(jsonNode);

var responseModel = JsonConvert.DeserializeObject<NotificationResponse>(jsonNode);
Console.WriteLine(responseModel.Status);

答案 1 :(得分:1)

更改为string jsonNode = JsonConvert.SerializeXmlNode(xmlNode.DocumentElement.SelectSingleNode("Status"));

        XmlDocument xmlNode = new XmlDocument();
        xmlNode.LoadXml("<Response xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Status>Ok</Status></Response>");
        string jsonNode = JsonConvert.SerializeXmlNode(xmlNode.DocumentElement.SelectSingleNode("Status"));

        var responseModel = JsonConvert.DeserializeObject<NotificationResponse>(jsonNode);