我通过套接字接收XML字符串,并希望将其转换为C#对象。
这些消息的格式为:
<msg>
<id>1</id>
<action>stop</action>
</msg>
这怎么做呢?
我通过套接字接收XML字符串,并希望将其转换为C#对象。
这些消息的格式为:
<msg>
<id>1</id>
<action>stop</action>
</msg>
这怎么做呢?
您需要使用安装在Windows SDK中的xsd.exe
工具,该工具安装在类似以下目录的目录中:
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
这会给你yourfile.xsd
文件,在第二步中,你可以再次使用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);
using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;
namespace Helpers
{
internal static class ParseHelpers
{
private static JavaScriptSerializer json;
private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }
public static Stream ToStream(this string @this)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(@this);
writer.Flush();
stream.Position = 0;
return stream;
}
public static T ParseXML<T>(this string @this) where T : class
{
var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
}
public static T ParseJSON<T>(this string @this) where T : class
{
return JSON.Deserialize<T>(@this.Trim());
}
}
}
public class JSONRoot
{
public catalog catalog { get; set; }
}
// ...
string xml = File.ReadAllText(@"D:\file.xml");
var catalog1 = xml.ParseXML<catalog>();
string json = File.ReadAllText(@"D:\file.json");
var catalog2 = json.ParseJSON<JSONRoot>();
尝试使用这种方法将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);
只需以管理员身份运行您的Visual Studio 2013... 复制您的Xml文件内容.. 进入Visual Studio 2013 > 编辑 > 粘贴特殊内容 > 将Xml粘贴为C#类 它将根据您的Xml文件内容创建您的c#类。
万一有人觉得这个有用:
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);
[XmlRoot("msg")]
public class Message
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("action")]
public string Action { get; set; }
}
然后您可以使用 ExtendedXmlSerializer 进行序列化和反序列化。
安装 您可以从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);
对于 Damian 给出的优秀回答,简而言之:
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);
}
}
我已经查看了所有截止至2020年7月24日的答案,必须有一种更简单、更熟悉的方法来解决这个问题,以下是该方法:
两种情况...第一种是XML字符串格式正确,也就是在遇到根元素之前,它以像<?xml version="1.0" encoding="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);
string xml = System.IO.File.ReadAllText(@"C:\test\books.xml");
var book = Dandraka.XmlUtilities.XmlSlurper.ParseText(xml);