我通过套接字接收XML字符串,并希望将这些转换为c#对象。
这些消息的形式是:
<msg>
<id>1</id>
<action>stop</action>
</msg>
如何做到这一点呢?
我通过套接字接收XML字符串,并希望将这些转换为c#对象。
这些消息的形式是:
<msg>
<id>1</id>
<action>stop</action>
</msg>
如何做到这一点呢?
当前回答
你可以像上面描述的那样生成类,也可以手动编写:
[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集成。
其他回答
你可以像上面描述的那样生成类,也可以手动编写:
[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集成。
在这个日期(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);
创建一个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;
}
以防有人觉得这个有用:
public static class XmlConvert
{
public static string SerializeObject<T>(T dataObject)
{
if (dataObject == null)
{
return string.Empty;
}
try
{
using (StringWriter stringWriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stringWriter, dataObject);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
return string.Empty;
}
}
public static T DeserializeObject<T>(string xml)
where T : new()
{
if (string.IsNullOrEmpty(xml))
{
return new T();
}
try
{
using (var stringReader = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
catch (Exception ex)
{
return new T();
}
}
}
你可以使用:
MyCustomObject myObject = new MyCustomObject();
string xmlString = XmlConvert.SerializeObject(myObject);
myObject = XmlConvert.DeserializeObject<MyCustomObject>(xmlString);
您可以使用xsd.exe在.Net中创建模式绑定类,然后使用XmlSerializer反序列化字符串:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx