Gre*_*egH 2 c# xml deserialization
我目前正在尝试修改类,以使模型上的文本属性包含某个节点(text)节点的所有内部文本。
给我一些问题的xml示例是:
<component>
<section>
<title>Reason for Visit</title>
<text>
<content ID="ID3EZZKACA">No Reason for Visit was given.</content>
</text>
</section>
</component>
Run Code Online (Sandbox Code Playgroud)
我的目标是使模型的text属性具有以下字符串:
"<content ID="ID0EAAKACA">No Reason for Visit was given.</content>"
目前,我的模型如下所示:
public partial class ComponentSection {
//other model properties here
private string textField;
[System.Xml.Serialization.XmlTextAttribute()]
public string text {
get {
return this.textField;
}
set {
this.textField = value;
}
}
//getters/setters for other properties here
}
Run Code Online (Sandbox Code Playgroud)
因此,我目前正在尝试通过使用注释来完成此操作,[System.Xml.Serialization.XmlTextAttribute()]但是当我这样做时,在对XML进行反序列化时,text属性始终通过null来实现。
正如我在评论中所说,从序列化开始通常更容易。对于上面的XML,这是一些类
public sealed class component
{
public section section { get; set; }
}
public sealed class section
{
public string title { get; set; }
public text text { get; set; }
}
public sealed class text
{
public content content { get; set; }
}
public sealed class content
{
public string text { get; set; }
public string ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,修改内容类以控制XML序列化:
public sealed class content
{
[XmlText]
public string text { get; set; }
[XmlAttribute]
public string ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下代码序列化实例:
static string ToXmlString<T>(T t)
{
var serializer = new XmlSerializer(t.GetType());
using (var sw = new System.IO.StringWriter())
{
serializer.Serialize(sw, t);
return sw.ToString();
}
}
static void Main(string[] args)
{
var c = new component { section = new section {
title = "Reason for Visit", text = new text { content = new content {
ID = "ID3EZZKACA", text = "No Reason for Visit was given." } } } };
string s = ToXmlString(c);
Console.WriteLine(s);
}
Run Code Online (Sandbox Code Playgroud)
结果是以下XML:
<?xml version="1.0" encoding="utf-16"?>
<component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http
://www.w3.org/2001/XMLSchema">
<section>
<title>Reason for Visit</title>
<text>
<content ID="ID3EZZKACA">No Reason for Visit was given.</content>
</text>
</section>
</component>
Run Code Online (Sandbox Code Playgroud)