我目前正在尝试修改我的类,以便我的模型上的文本属性包含某个节点的所有内部文本(text
) node.
给我带来问题的 xml 示例是:
<component>
<section>
<title>Reason for Visit</title>
<text>
<content ID="ID3EZZKACA">No Reason for Visit was given.</content>
</text>
</section>
</component>
我的目标是我的模型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
}
所以,我目前正在尝试通过使用注释来完成此任务[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; }
}
然后,修改content上课到控制 XML 序列化 https://msdn.microsoft.com/en-us/library/83y7df3e(v=vs.110).aspx:
public sealed class content
{
[XmlText]
public string text { get; set; }
[XmlAttribute]
public string ID { get; set; }
}
然后,您可以使用以下代码序列化实例:
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);
}
结果是以下 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)