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

仅固定外层Output标签时,如何将XML转换为含内部字符串内容的对象?

提取XML中标签内的内容并转为字符串

场景说明

现有被<Output>标签包裹的XML字符串,内部标签结构不固定,需要提取标签内的内容转为字符串,存入自定义Output类的content属性,核心需求是判断该内容是否为空。


方法1:正则表达式(简单场景适用)

适合确定没有嵌套<Output>标签、XML结构简单的场景,代码示例(C#):

using System;
using System.Text.RegularExpressions;

public class Output
{
    private string content;
    public string Content 
    { 
        get => content; 
        set => content = value; 
    }
}

class Program
{
    static void Main()
    {
        string inputXml = @"<Output>
    <tag1>xxxxx</tag1>
    <tag2>xxxxx</tag2>
    <tag3>xxxxx</tag3>
</Output>";

        // 匹配<Output>与</Output>之间的所有内容(含换行)
        Match match = Regex.Match(inputXml, @"<Output>([\s\S]*?)</Output>", RegexOptions.IgnoreCase);
        Output outputObj = new Output();
        
        outputObj.Content = match.Success ? match.Groups[1].Value.Trim() : string.Empty;

        // 判断内容是否为空
        bool isEmpty = string.IsNullOrWhiteSpace(outputObj.Content);
        Console.WriteLine(isEmpty ? "Output内容为空" : "Output内容不为空");
    }
}

注:[\s\S]*?是匹配所有字符(含换行)的非贪婪模式,避免匹配到多个</Output>标签;IgnoreCase用于忽略标签大小写,不需要可移除。


方法2:XML解析器(推荐,鲁棒性强)

如果XML结构复杂(含嵌套标签、特殊字符),用官方XML解析器更可靠,避免正则的局限性,代码示例(C#):

using System;
using System.Xml;

public class Output
{
    private string content;
    public string Content 
    { 
        get => content; 
        set => content = value; 
    }
}

class Program
{
    static void Main()
    {
        string inputXml = @"<Output>
    <tag1>xxxxx</tag1>
    <tag2>xxxxx</tag2>
    <tag3>xxxxx</tag3>
</Output>";

        Output outputObj = new Output();
        XmlDocument doc = new XmlDocument();
        
        try
        {
            doc.LoadXml(inputXml);
            XmlNode outputNode = doc.SelectSingleNode("//Output");
            
            outputObj.Content = outputNode != null ? outputNode.InnerXml.Trim() : string.Empty;
        }
        catch (XmlException ex)
        {
            // 处理XML格式错误
            Console.WriteLine("XML格式错误:" + ex.Message);
            outputObj.Content = string.Empty;
        }

        bool isEmpty = string.IsNullOrWhiteSpace(outputObj.Content);
        Console.WriteLine(isEmpty ? "Output内容为空" : "Output内容不为空");
    }
}

注:InnerXml直接获取<Output>节点内的所有XML内容,自动处理特殊字符和嵌套结构,适合生产环境使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:09:51