如何在 C# 上反序列化一个 XML 行



我在服务上运行一个方法,该方法只在字符串上返回一行 XML:

<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>

我试图以这种方式反序列化这一行:

var strXml = "<boolean xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>true</boolean>";
XmlSerializer serializer = new XmlSerializer(typeof(bool));
bool success = false;
using (TextReader reader = new StringReader(strXml))
{
    success = (bool)serializer.Deserialize(reader);
}

但是在生产线上

success = (bool)serializer.Deserialize(reader);

引发异常:

There is an error in XML document (1, 2)

有什么线索可以告诉我能做什么吗?我对 XML 序列化很陌生。

您可以使用 XElement.Parse 来解析任何单个元素:

XElement element = XElement.Parse(strXml);

样本:

string strXml = @"<boolean xmlns =""http://schemas.microsoft.com/2003/10/Serialization/"">true</boolean>";
bool success = (bool)XElement.Parse(strXml);  // true

在线试用

你可以

从根节点中获取值并尝试将其解析为布尔值:

//load into XDocument
var doc = XDocument.Parse("<boolean xmlns="http://schemas.microsoft.com/2003/10/Serialization/">true</boolean>");
bool success = bool.Parse(doc.Root.Value); //true

该 XML 看起来像是用 DataContractSerializer 创建的,因此请使用:

var serializer = new DataContractSerializer(typeof(bool));        
using (var sr = new StringReader(xml))
using (var xr = XmlReader.Create(sr))
{
    var success = (bool) serializer.ReadObject(xr);
}

最新更新