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

这些消息的形式是:

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

如何做到这一点呢?


当前回答

另一种高级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

其他回答

除了这里的其他答案之外,您还可以自然地使用XmlDocument类(用于类似XML dom的读取)或XmlReader(仅向前的快速读取器)来“手动”执行此操作。

简化达米安的回答,

public static T ParseXml<T>(this string value) where T : class
{
    var xmlSerializer = new XmlSerializer(typeof(T));
    using (var textReader = new StringReader(value))
    {
        return (T) xmlSerializer.Deserialize(textReader);
    }
}

创建一个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;
}

另一种高级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。

但是(警告:这里是无耻的自我推销)我刚刚发布了一个小包,在这里,你不必使用它。你只要说:

string xml = System.IO.File.ReadAllText(@"C:\test\books.xml");
var book = Dandraka.XmlUtilities.XmlSlurper.ParseText(xml);

这就是它的字面意思,没有其他需要。最重要的是,如果xml发生变化,对象也会自动发生变化。

如果您喜欢直接下载dll, github页面在这里。