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

这些消息的形式是:

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

如何做到这一点呢?


当前回答

您可以使用xsd.exe在.Net中创建模式绑定类,然后使用XmlSerializer反序列化字符串:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

其他回答

你需要使用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);

简单地运行你的Visual Studio 2013管理… 复制Xml文件的内容。 进入Visual Studio 2013 >编辑>粘贴特殊>将Xml粘贴为c#类 它将根据Xml文件内容创建c#类。

在这个日期(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

创建一个DTO作为CustomObject

使用下面的方法使用JAXB将XML字符串转换为DTO

private static CustomObject getCustomObject(final String ruleStr) {
    CustomObject customObject = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(CustomObject.class);
        final StringReader reader = new StringReader(ruleStr);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        customObject = (CustomObject) jaxbUnmarshaller.unmarshal(reader);
    } catch (JAXBException e) {
        LOGGER.info("getCustomObject parse error: ", e);
    }
    return customObject;
}