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