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

如何在C#中解析XML并提取iban元素

嘿,这有几种在C#里提取你给的XML中iban元素内容的实用方法,都是日常开发里常用的:

先提个小细节:你提供的XML里<country>标签的闭合有问题,应该改成</country>,不然解析时会报错哦。

方法1:使用XmlDocument(传统DOM操作)

适合熟悉旧版XML处理逻辑的场景,通过XPath定位节点:

using System.Xml;

// 假设XML内容已存储在字符串中
string xmlContent = @"<result> <iban>GB20ULSB98006054100029</iban> <account>54100029</account> <sort_code>980060</sort_code> <bank>ULSTER BANK LTD</bank> <branch>BELFAST CITY OFFICE 1</branch> <bic>ULSBGB2BXXX</bic> <address>PO BOX 232 11-16 DONEGALL SQUARE EAST </address> <city>BT1 5UB</city> <country>GB</country> <phone>028 90244112</phone> </result>";

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

// 通过XPath精准定位iban节点
XmlNode ibanNode = doc.SelectSingleNode("/result/iban");
if (ibanNode != null)
{
    string ibanValue = ibanNode.InnerText;
    Console.WriteLine(ibanValue); // 输出:GB20ULSB98006054100029
}
方法2:使用XDocument(LINQ to XML,推荐)

这是.NET里更现代、简洁的处理方式,结合LINQ语法让代码更清爽:

using System.Xml.Linq;

string xmlContent = @"<result> <iban>GB20ULSB98006054100029</iban> <account>54100029</account> <sort_code>980060</sort_code> <bank>ULSTER BANK LTD</bank> <branch>BELFAST CITY OFFICE 1</branch> <bic>ULSBGB2BXXX</bic> <address>PO BOX 232 11-16 DONEGALL SQUARE EAST </address> <city>BT1 5UB</city> <country>GB</country> <phone>028 90244112</phone> </result>";

XDocument xDoc = XDocument.Parse(xmlContent);

// 安全提取iban内容,避免空引用异常
string ibanValue = xDoc.Descendants("iban").FirstOrDefault()?.Value;
if (!string.IsNullOrEmpty(ibanValue))
{
    Console.WriteLine(ibanValue);
}
方法3:使用XmlSerializer(序列化实体类)

如果这个XML结构是你需要频繁处理的,把它映射成实体类会让代码的可读性和维护性大幅提升:
首先定义对应实体类:

using System.Xml.Serialization;

[XmlRoot("result")]
public class BankResult
{
    [XmlElement("iban")]
    public string Iban { get; set; }
    
    // 可以按需添加其他元素对应的属性
    [XmlElement("account")]
    public string Account { get; set; }
    [XmlElement("sort_code")]
    public string SortCode { get; set; }
    // ... 其他属性省略
}

然后通过序列化解析XML:

using System.Xml.Serialization;
using System.IO;

string xmlContent = @"<result> <iban>GB20ULSB98006054100029</iban> <account>54100029</account> <sort_code>980060</sort_code> <bank>ULSTER BANK LTD</bank> <branch>BELFAST CITY OFFICE 1</branch> <bic>ULSBGB2BXXX</bic> <address>PO BOX 232 11-16 DONEGALL SQUARE EAST </address> <city>BT1 5UB</city> <country>GB</country> <phone>028 90244112</phone> </result>";

XmlSerializer serializer = new XmlSerializer(typeof(BankResult));
using (StringReader reader = new StringReader(xmlContent))
{
    BankResult result = (BankResult)serializer.Deserialize(reader);
    Console.WriteLine(result.Iban); // 直接通过属性获取值
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:02:44