在 Windows 8.1 商店应用程序 c# 中从字符串转换为对象 [英] Conversion from string to object in Windows 8.1 store app c#

查看:28
本文介绍了在 Windows 8.1 商店应用程序 c# 中从字符串转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串转换为具有值的对象.我的意思是假设我有一个包含 XML 代码的字符串,例如:

I want to covert to string into object with value. I mean let's say i have string that has XML code inside like:

代码片段:

String response =@"<?xml version=""1.0"" encoding=""utf-8""?>\r\n
<Request>\r\n  
<TransactionType>ADMIN</TransactionType>\r\n   
<Username>abc</Username>\r\n  
<Password>def</Password>\r\n  
</Request>";

我有一个类,它具有 Xml 中提到的所有属性,例如

I have a Class that has all the properties which mentioned in Xml like

类响应类

String UserName;

String Password;

String Transaction;

如何在没有字符串解析的情况下设置 ResponseClass 对象中的所有值?我已经尝试过序列化,但由于 API 的限制,它在 Windows 8.1 应用商店项目中给我带来了一些问题.

How can I set all the values in ResponseClass object without string parsing? I have tried it with serialization but it gives me some problem in windows 8.1 app store project due to limitation in API.

有什么办法可以把它排序吗?

Is there any way to get it sorted?

谢谢

推荐答案

这是使用 XDocument.Parse(String) 来自 System.Xml.Linq:

String response = @"<?xml version=""1.0"" encoding=""utf-8""?>
    <Request> 
        <TransactionType>ADMIN</TransactionType>   
        <Username>abc</Username> 
        <Password>def</Password> 
    </Request>";

var xml = XDocument.Parse(response);
var request = xml.Element("Request");

var responseObject = new ResponseClass()
{
    UserName = request.Element("Username").Value,
    Password = request.Element("Password").Value,
    Transaction = request.Element("TransactionType").Value,
};

或者,如果 Windows 商店应用程序支持它,您可以使用内置的 XmlSerializer(如果没有,你可以忽略这一点).只需使用 XmlRootXmlElement 属性定义您的类,如下所示:

Or, if the Windows store apps support it, you can use the built in XmlSerializer (if not, you can just ignore this bit). Just define your class using the XmlRoot and XmlElement attributes like this:

[XmlRoot("Request")]
public class ResponseClass
{
    [XmlElement("Username")]
    public String UserName { get; set; }

    [XmlElement("Password")]
    public String Password { get; set; }

    [XmlElement("TransactionType")]
    public String Transaction { get; set; }
}

然后使用创建一个 XmlSerializerStringReader 来反序列化它:

and then use the create an XmlSerializer and StringReader to deserialize it:

String response = @"<?xml version=""1.0"" encoding=""utf-8""?>
    <Request> 
        <TransactionType>ADMIN</TransactionType>   
        <Username>abc</Username> 
        <Password>def</Password> 
    </Request>";

var serializer = new XmlSerializer(typeof(ResponseClass));
ResponseClass responseObject;

using (var reader = new StringReader(response))
{
    responseObject = serializer.Deserialize(reader) as ResponseClass;
}

这篇关于在 Windows 8.1 商店应用程序 c# 中从字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆