You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将XML文件转换为C#对象?无法获取Group标签内文本

解决XML转C#对象时Group标签文本无法读取的问题

你的问题在于Group标签存在两种形态:一种包含子元素(<NV>、<Property>),另一种仅包含纯文本。当前的Group类没有对应属性来捕获标签内的文本内容,需要添加[XmlText]特性标记的属性来处理这种情况。

修改后的类定义

using System.Collections.Generic;
using System.Xml.Serialization;

[XmlRoot(ElementName = "Property")]
public class Property
{
    [XmlElement(ElementName = "NV")]
    public string NV { get; set; }

    [XmlElement(ElementName = "Value")]
    public string Value { get; set; }
}

[XmlRoot(ElementName = "Group")]
public class Group
{
    [XmlElement(ElementName = "NV")]
    public string NV { get; set; }

    [XmlElement(ElementName = "Property")]
    public List<Property> Property { get; set; }

    // 添加XmlText属性捕获Group标签内的纯文本
    [XmlText]
    public string TextContent { get; set; }
}

[XmlRoot(ElementName = "Main")]
public class Main
{
    [XmlElement(ElementName = "Group")]
    public List<Group> Group { get; set; }
}

说明

  • [XmlText]特性用于映射XML元素的文本内容,当Group标签仅包含纯文本时,内容会被赋值到TextContent属性中;当Group包含子元素时,TextContent会为null或空字符串(取决于XML是否有空白字符)。
  • 反序列化示例:
using System.IO;
using System.Xml.Serialization;

// 读取XML文件
var serializer = new XmlSerializer(typeof(Main));
using var reader = new StreamReader("your-xml-file-path.xml");
var mainObj = (Main)serializer.Deserialize(reader);

// 遍历Group列表查看结果
foreach (var group in mainObj.Group)
{
    if (!string.IsNullOrEmpty(group.TextContent))
    {
        Console.WriteLine($"纯文本Group:{group.TextContent}");
    }
    else
    {
        Console.WriteLine($"带子元素的Group,NV值:{group.NV}");
        foreach (var prop in group.Property)
        {
            Console.WriteLine($"  属性:{prop.NV} = {prop.Value}");
        }
    }
}

内容的提问来源于stack exchange,提问作者mike1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:42:03