如何用C# XmlTextReader仅提取XML中的Tax金额?
修正XmlTextReader代码仅提取Tax金额的方案
没问题,我帮你调整代码解决这个问题~咱们先看问题根源:你当前的代码只要碰到<Type>元素就会读取后续的<Amount>,不管这个Type是Principal还是Tax,所以才会把两个金额都输出。要只获取Tax对应的金额,咱们只需要多一步判断——确认Type的内容是"Tax"之后再读取Amount就行。
修正后的完整代码
using System; using System.Xml; namespace democonsole { class Program { static void Main(string[] args) { // 记得把这里替换成你的亚马逊订单XML文件的实际路径 using (XmlTextReader xtr = new XmlTextReader("your_amazon_order.xml")) { while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "City") { string city = xtr.ReadElementContentAsString(); Console.WriteLine($"City = {city}"); } if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "Type") { // 先读取Type的内容,判断是否为Tax string typeValue = xtr.ReadElementContentAsString(); if (typeValue.Equals("Tax", StringComparison.OrdinalIgnoreCase)) { // 仅当Type是Tax时,读取对应的Amount xtr.ReadToFollowing("Amount"); decimal taxAmount = xtr.ReadElementContentAsDecimal(); Console.WriteLine($"Tax = {taxAmount}"); } } } } } } }
关键修改说明
- 添加Type内容判断:在读取
<Type>元素后,先获取它的文本内容,只有当内容等于"Tax"时,才继续读取后面的<Amount>,这样就过滤掉了Principal对应的金额。 - 使用using语句管理资源:把
XmlTextReader放在using块里,这样代码执行完毕后会自动释放资源,避免内存泄漏,这是.NET中处理资源类的最佳实践。 - 优化输出格式:用字符串插值
$""替代拼接,让输出代码更易读。 - 忽略大小写的判断:用
StringComparison.OrdinalIgnoreCase做判断,避免因为XML里的Type值大小写不一致(比如"tax")导致漏读。
测试验证
用你提供的XML文件测试时,代码会输出:
City = SAN JOSE Tax = 1.39
完美符合你只获取Tax金额的需求~
内容的提问来源于stack exchange,提问作者steve
相关产品推荐
相关产品推荐

