在 C# 中从 XML 中删除元素 [英] Removing Element from XML in C#

查看:30
本文介绍了在 C# 中从 XML 中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是xml,我需要删除代码等于ZOOMLA"的元素短信.我正在使用 C# 代码,如下所示,但它不起作用.并给我对象引用错误"

below is the xml and i need to remove the Element SMS where code equals to "ZOOMLA". i am using C# code as below but it does not work. and gives me "object reference error"

 XDocument doc = XDocument.Parse (xml);
 XElement sms = (from xml2 in doc.Descendants ("SMSList").Descendants ("SMS") where xml2.Attribute ("Code").Value == code select xml2).FirstOrDefault ();
 sms.Remove ();

<小时>

<?xml version="1.0" encoding="utf-16" ?>
    <Parent>
        <ServiceList />
        <VoiceList />
        <SMSList>
            <SMS>
                <Code>ZOOMLA</Code>
                <Name>Zoom Limited</Name>
                <SubType>Prepaid</SubType>
                <Fields>
                    <Field>
                        <ID>222</ID>
                        <Name>Charges</Name>
                        <CValue>1</CValue>
                        <Priority>0</Priority>
                    </Field>
                </Fields>
            </SMS>
        </SMSList>
        <DataList />
        <LBCOffer />
    </Parent>

推荐答案

您当前正在寻找 Code 属性,而在您的 XML 中,它是一个 元素.所以 FirstOrDefault() 没有找到任何东西并返回 null,因此在下一个语句中出现异常.

You're currently looking for a Code attribute, whereas in your XML it's an element. So FirstOrDefault() doesn't find anything and returns null, hence the exception on the next statement.

此外,您可以使用 LINQIEnumerable 上的 XML Remove 扩展方法 - 这意味着它将删除所有匹配元素,因此它不会失败如果没有.(如果您真的只想删除第一个匹配项,您始终可以在此处使用 Take(1).)

Additionally, you can just use the LINQ to XML Remove extension method on IEnumerable<T> - that means it will remove all matching elements, so it won't fail if there aren't any. (If you really want to only remove the first match, you could always use Take(1) here.)

XDocument doc = XDocument.Parse(xml);
doc.Descendants("SMSList")
   .Descendants("SMS")
   .Where(x => (string) x.Element("Code") == code)
   .Remove();

这篇关于在 C# 中从 XML 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆