使用XmlSerializer方式
时间: 2024-10-06 11:04:35 浏览: 30
在C#中,如果你想要使用`XmlSerializer`来序列化和反序列化XML数据,首先你需要创建一个类(数据契约),这个类将会映射到XML文档中的结构。假设你有一个`KrosyData`类对应于上面的XML:
```csharp
[Serializable]
public class KrosyData
{
[XmlElement("header")]
public Header header { get; set; }
[XmlElement("body")]
public Body body { get; set; }
}
public class Header
{
[XmlElement("requestID")]
public string requestID { get; set; }
public SourceHost sourceHost { get; set; }
public TargetHost targetHost { get; set; }
}
public class SourceHost
{
[XmlElement("hostname")]
public string hostname { get; set; }
[XmlElement("ipAddress")]
public string ipAddress { get; set; }
[XmlElement("macAddress")]
public string macAddress { get; set; }
}
public class TargetHost
{
[XmlElement("hostname")]
public string hostname { get; set; }
}
public class Body
{
[XmlElement("visualControl")]
public VisualControl visualControl { get; set; }
}
public class VisualControl
{
[XmlElement("workingRequest")]
public WorkingRequest workingRequest { get; set; }
}
public class WorkingRequest
{
[XmlAttribute("scanned")]
public DateTime scanned { get; set; }
[XmlAttribute("intksk")]
public long intksk { get; set; }
}
```
接下来,你可以使用`XmlSerializer`进行序列化和反序列化操作:
**序列化(将对象转换为XML):**
```csharp
KrosyData krosyData = new KrosyData { header = new Header(), body = new Body() };
// ...填充header和body属性
using (var stream = File.CreateText("output.xml"))
{
var serializer = new XmlSerializer(typeof(KrosyData));
serializer.Serialize(stream, krosyData);
}
```
**反序列化(从XML恢复对象):**
```csharp
if (!File.Exists("output.xml")) throw new FileNotFoundException();
using (var stream = File.OpenText("output.xml"))
{
var serializer = new XmlSerializer(typeof(KrosyData));
KrosyData deserializedData = (KrosyData)serializer.Deserialize(stream);
// Now you can access the deserialized properties like this:
string requestID = deserializedData.header.requestID;
}
```
注意,`XmlSerializer`适用于简单的、非嵌套的数据结构,对于复杂的XML结构,可能会变得不够灵活。这时可以考虑使用`XElement`或`Json.NET`等其他库。
阅读全文