我通过套接字接收XML字符串,并希望将这些转换为c#对象。
这些消息的形式是:
<msg>
<id>1</id>
<action>stop</action>
</msg>
如何做到这一点呢?
我通过套接字接收XML字符串,并希望将这些转换为c#对象。
这些消息的形式是:
<msg>
<id>1</id>
<action>stop</action>
</msg>
如何做到这一点呢?
当前回答
除了这里的其他答案之外,您还可以自然地使用XmlDocument类(用于类似XML dom的读取)或XmlReader(仅向前的快速读取器)来“手动”执行此操作。
其他回答
创建一个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.exe在.Net中创建模式绑定类,然后使用XmlSerializer反序列化字符串:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx
尝试此方法将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。
另一种高级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