【问题标题】:How to deserialize just one XML line on C#?如何在 C# 上仅反序列化一个 XML 行?
【发布时间】:2017-08-21 16:33:04
【问题描述】:

我在一个服务上运行一个方法,它只返回一个字符串中的一行 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 序列化很陌生。

【问题讨论】:

    标签: c# xml serialization deserialization


    【解决方案1】:

    您可以使用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
    

    Try it online

    【讨论】:

      【解决方案2】:

      那个 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);
      }
      

      【讨论】:

        【解决方案3】:

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

        //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
        

        【讨论】:

          猜你喜欢
          • 2010-09-27
          • 1970-01-01
          • 2015-04-13
          • 1970-01-01
          • 1970-01-01
          • 2011-05-12
          • 2012-09-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多