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

求助:.NET中自定义XML字符串的C#解析实现

修复XML语法并实现C#解析

首先你的XML存在语法错误:第二个<test3>标签中,xxxxxx"缺少属性名称,需补充为value="xxxxxx",修正后的XML如下:

<?xml version="1.0" encoding="UTF-8"?> 
<test1> 
<test2>  
<test3 name="responseCode" value="xxxxx" />  
<test3 name="responseDescription" value="xxxxxx" />  
</test2>  
</test1>

以下提供两种常见的C#解析实现方式:

方式一:使用XmlDocument(传统DOM解析)

using System;
using System.Xml;

class XmlParser
{
    static void Main()
    {
        string xmlContent = @"<?xml version=""1.0"" encoding=""UTF-8""?> 
<test1> 
<test2>  
<test3 name=""responseCode"" value=""xxxxx"" />  
<test3 name=""responseDescription"" value=""xxxxxx"" />  
</test2>  
</test1>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlContent);

        // 获取所有test3节点
        XmlNodeList test3Nodes = doc.SelectNodes("//test3");
        foreach (XmlNode node in test3Nodes)
        {
            string name = node.Attributes["name"].Value;
            string value = node.Attributes["value"].Value;
            Console.WriteLine($"{name}: {value}");
        }
    }
}

方式二:使用LINQ to XML(简洁现代方式)

using System;
using System.Linq;
using System.Xml.Linq;

class LinqXmlParser
{
    static void Main()
    {
        string xmlContent = @"<?xml version=""1.0"" encoding=""UTF-8""?> 
<test1> 
<test2>  
<test3 name=""responseCode"" value=""xxxxx"" />  
<test3 name=""responseDescription"" value=""xxxxxx"" />  
</test2>  
</test1>";

        XDocument doc = XDocument.Parse(xmlContent);

        var test3Elements = doc.Descendants("test3");
        foreach (var element in test3Elements)
        {
            string name = element.Attribute("name").Value;
            string value = element.Attribute("value").Value;
            Console.WriteLine($"{name}: {value}");
        }
    }
}

若原XML的错误并非笔误,而是实际返回的格式问题,需先通过字符串处理(比如正则匹配补全缺失属性名)修复XML,再执行解析逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:45:27