C# - XML - 从某个元素作为字符串对待内部XML [英] C# - XML - Treat inner xml from a certain element as string
问题描述
我有下面的XML:
<Plan>
<Error>0</Error>
<Description>1</Description>
<Document>
<ObjectID>06098INF1761320</ObjectID>
<ced>109340336</ced>
<abstract>DAVID STEVENSON</abstract>
<ced_a />
<NAM_REC />
<ced_ap2 />
</Document>
</Plan>
我这个反序列化:
I deserialize it with this:
[XmlRoot("Plan")]
public class EPlan
{
[XmlElement("Error")]
public string Error { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
[XmlElement("Document")]
public List<EDocument> Documents { get; set; }
}
public class EDocument
{
[XmlText]
public string Document { get; set; }
}
问题是我想要的元素一号文件包含其内XML作为一个字符串,我的意思是,对象应该具有以下值:
The issue is that I want the element "Document" to contain its inner XML as a single string, I mean, the object should have these values:
obj.Error = "0";
obj.Description = "1";
obj.Documents[0].Document = "<ObjectID>06098INF1761320</ObjectID><ced>109340336</ced><abstract>DAVID STEVENSON</abstract><ced_a /><NAM_REC /><ced_ap2 />";
不过,我前面提到的方式保持检索NULL文档属性。
But the way I mentioned before keeps retrieving a NULL "Document" property.
是否可以达到我想要的行为?任何帮助,将不胜感激。
Is it possible to achieve the behaviour I want? Any help would be appreciated.
推荐答案
XMLTEXT
需要一个文本节点,但你有什么实际上是元素节点。我不知道是否有这样做直接的方式,但你可以有一个 XmlAnyElement将
节点收集反序列化的结果,事后你在一个将它们合并字符串如果这是你所需要的,如下面的例子。
XmlText
expects a text node, but what you have are actually element nodes. I don't know if there's a direct way to do that, but you can have a XmlAnyElement
node to collect the result of the deserialization, and afterwards you merge them in a single string if that's what you need, as shown in the example below.
[XmlRoot("Plan")]
public class EPlan
{
[XmlElement("Error")]
public string Error { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
[XmlElement("Document")]
public List<EDocument> Documents { get; set; }
}
[XmlType]
public class EDocument
{
private string document;
[XmlAnyElement]
[EditorBrowsable(EditorBrowsableState.Never)]
public XmlElement[] DocumentNodes { get; set; }
[XmlIgnore]
public string Document
{
get
{
if (this.document == null)
{
StringBuilder sb = new StringBuilder();
foreach (var node in this.DocumentNodes)
{
sb.Append(node.OuterXml);
}
this.document = sb.ToString();
}
return this.document;
}
}
}
static void Test()
{
string xml = @"<Plan>
<Error>0</Error>
<Description>1</Description>
<Document>
<ObjectID>06098INF1761320</ObjectID>
<ced>109340336</ced>
<abstract>DAVID STEVENSON</abstract>
<ced_a />
<NAM_REC />
<ced_ap2 />
</Document>
<Document>
<ObjectID>id2</ObjectID>
<ced>ced2</ced>
<abstract>abstract2</abstract>
<ced_a />
<NAM_REC />
<ced_ap2 />
</Document>
</Plan>";
XmlSerializer xs = new XmlSerializer(typeof(EPlan));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
EPlan obj = xs.Deserialize(ms) as EPlan;
Console.WriteLine(obj.Documents[0].Document);
}
这篇关于C# - XML - 从某个元素作为字符串对待内部XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!