在c#中获取具有指定标题的XElement

时间:2014-09-18 07:08:36

标签: c# xml asp.net-mvc-4

这里是xml文档,我需要从c#中的servicelist获取具有指定标题的服务。假设我有标题为“收集呼叫和短信”的服务,如下所示我想获得此服务,以便我可以从XDocument中删除它。请注意,我将此xml作为字符串从数据库中获取

C#

XDocument doc = XDocument.Parse(xmlstring);

XML文档

  <?xml version="1.0" encoding="utf-16" ?> 
  - <ServiceList>
  - <Service>
  <COMPAT>2</COMPAT> 
  <EQUIPID>0</EQUIPID> 
  <TITLE>Collect Call and SMS</TITLE> 
  <SMSCOMMAND>0</SMSCOMMAND> 
  <DIALCOMMAND>123</DIALCOMMAND> 
  <DEACTIVATIONCOMMAND>0</DEACTIVATIONCOMMAND> 
  <MODE>Dial</MODE> 
 <DETAIL>Here you go</DETAIL> 
 <IMAGE>2014-18-9--11-47-33</IMAGE> 
 - <LONGDESC>
 - <![CDATA[ <p>Service</p>
 <p>Service</p>
 ]]> 
 </LONGDESC>
 - <Mechanism>
  <Title>Mech Title</Title> 
 <Description /> 
 <Trigger>Mech Trigger</Trigger> 
 <Controls>1</Controls> 
</Mechanism>
</Service>
- <Service>
<COMPAT>2</COMPAT> 
<EQUIPID>0</EQUIPID> 
<TITLE>MS Call and SMS</TITLE> 
<SMSCOMMAND>SUB,6104</SMSCOMMAND> 
<DIALCOMMAND>0</DIALCOMMAND> 
<DEACTIVATIONCOMMAND>UNSUB,6104</DEACTIVATIONCOMMAND> 
<MODE>SMS</MODE> 
<DETAIL>Service</DETAIL> 
<IMAGE>2014-18-9--11-47-59</IMAGE> 
- <LONGDESC>
- <![CDATA[ <p>P<br />P<br />P&nbsp;</p>
]]> 
</LONGDESC>
- <Mechanism>
 <Title>Mech Title</Title> 
 <Description>Service</Description> 
 <Trigger>Mech Trigger</Trigger> 
 <Controls>1</Controls> 
 </Mechanism>
 </Service>
 </ServiceList>

1 个答案:

答案 0 :(得分:1)

var xd = XDocument.Parse(xml);

xd.Root.Elements("Service") // Enumerate the service elements
    .Where 
    (
        x=>
        (string)x.Element("TITLE") == "Collect Call and SMS"
    )                       // Find the ones you are interested in
    .Remove();              //Remove them from the document