gpt4 book ai didi

C# XML 反序列化。将节点中的所有内部文本读入字符串属性

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:43 25 4
gpt4 key购买 nike

我目前正在尝试修改我的类,以便我的模型上的文本属性包含某个节点 ( text) 节点的所有内部文本。

给我带来问题的 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; }
}

然后,将内容类修改为control XML serialization :

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>

关于C# XML 反序列化。将节点中的所有内部文本读入字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com