我通过套接字接收XML字符串,并希望将这些转换为c#对象。

这些消息的形式是:

<msg>
   <id>1</id>
   <action>stop</action>
</msg>

如何做到这一点呢?


当前回答

你需要使用xsd.exe工具,它会被安装到一个类似于Windows SDK的目录中:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

在64位计算机上:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin

在Windows 10电脑上:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

在第一次运行时,您使用XSD .exe并将示例XML转换为XSD文件(XML模式文件):

xsd yourfile.xml

这会给你你的文件。在第二步中,您可以再次使用xsd.exe将其转换为c#类:

xsd yourfile.xsd /c

这应该会给你一个文件yourfile.cs,它将包含一个c#类,你可以使用它来反序列化你得到的XML文件-类似于:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));

在大多数情况下都能很好地工作。

更新:XML序列化器将接受任何流作为它的输入-文件或内存流都可以:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);

或者使用StringReader:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);

其他回答

在这个日期(2020-07-24),我已经看过了所有的答案,必须有一个更简单、更熟悉的方法来解决这个问题,这就是下面。

两个场景……一个是XML字符串是否格式良好,即它以<?XML版本="1.0"编码="utf-16"?>或类似的值,然后再遇到根元素,即问题中的<msg>。另一种是如果它不是良好形式的,即只有根元素(例如问题中的<msg>)和它的子节点。

首先,只是一个简单的类,其中包含以不区分大小写的名称匹配XML中根节点的子节点的属性。所以,从问题来看,它会是这样的…

public class TheModel
{
    public int Id { get; set; }
    public string Action { get; set; }
}

下面是剩下的代码…

// These are the key using statements to add.
using Newtonsoft.Json;
using System.Xml;

bool isWellFormed = false;
string xml =  = @"
<msg>
   <id>1</id>
   <action>stop</action>
</msg>
";

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
if (isWellFormed)
{
    xmlDocument.RemoveChild(xmlDocument.FirstChild); 
    /* i.e. removing the first node, which is the declaration part. 
    Also, if there are other unwanted parts in the XML, 
    write another similar code to locate the nodes 
    and remove them to only leave the desired root node 
    (and its child nodes).*/
}

var serializedXmlNode = JsonConvert.SerializeXmlNode(
            xmlDocument, 
            Newtonsoft.Json.Formatting.Indented, 
            true
            );
var theDesiredObject = JsonConvert.DeserializeObject<TheModel>(serializedXmlNode);

另一种高级xsd到c#类生成工具:xsd2code.com。这个工具非常方便和强大。它比Visual Studio中的xsd.exe工具有更多的自定义。xsd2code++可以定制为使用列表或数组,并支持包含大量Import语句的大型模式。

注意一些特征,

Generates business objects from XSD Schema or XML file to flexible C# or Visual Basic code. Support Framework 2.0 to 4.x Support strong typed collection (List, ObservableCollection, MyCustomCollection). Support automatic properties. Generate XML read and write methods (serialization/deserialization). Databinding support (WPF, Xamarin). WCF (DataMember attribute). XML Encoding support (UTF-8/32, ASCII, Unicode, Custom). Camel case / Pascal Case support. restriction support ([StringLengthAttribute=true/false], [RegularExpressionAttribute=true/false], [RangeAttribute=true/false]). Support large and complex XSD file. Support of DotNet Core & standard

尝试此方法将Xml转换为对象。它正是为你正在做的事情而做的:

protected T FromXml<T>(String xml)
{
    T returnedXmlClass = default(T);

    try
    {
        using (TextReader reader = new StringReader(xml))
        {
            try
            {
                returnedXmlClass = 
                    (T)new XmlSerializer(typeof(T)).Deserialize(reader);
            }
            catch (InvalidOperationException)
            {
                // String passed is not XML, simply return defaultXmlClass
            }
        }
    }
    catch (Exception ex)
    {
    }

    return returnedXmlClass ;        
}

使用下面的代码调用它:

YourStrongTypedEntity entity = FromXml<YourStrongTypedEntity>(YourMsgString);

如果您有xml消息的xsd,那么您可以使用. net xsd.exe工具生成c#类。

然后可以使用这个. net类来生成xml。

你可以像上面描述的那样生成类,也可以手动编写:

[XmlRoot("msg")]
public class Message
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("action")]
    public string Action { get; set; }
}

然后可以使用ExtendedXmlSerializer进行序列化和反序列化。

Instalation 您可以从nuget安装ExtendedXmlSerializer或运行以下命令:

Install-Package ExtendedXmlSerializer

序列化:

var serializer = new ConfigurationContainer().Create();
var obj = new Message();
var xml = serializer.Serialize(obj);

反序列化

var obj2 = serializer.Deserialize<Message>(xml);

这个序列化器支持:

从标准XMLSerializer反序列化xml 序列化类,结构,泛型类,基本类型,泛型列表和字典,数组,enum 具有属性接口的序列化类 序列化循环引用和引用Id 旧版本xml的反序列化 属性加密 自定义序列化器 支持XmlElementAttribute和XmlRootAttribute POCO——所有配置(迁移、自定义序列化器……)都在类之外

ExtendedXmlSerializer支持。net 4.5或更高版本和。net Core。你可以将它与WebApi和AspCore集成。