简体   繁体   中英

in C# how to select specific Data from an XMLDocument?

i got below response through web request

<Shofar Target_="Base" >
  <RapidOnSite_Pump Key="1" State="Idle" Amount="20" /> 
  <RapidOnSite_Pump Key="2" State="Idle" Amount="15" /> 
  <RapidOnSite_Pump Key="3" State="Despencing" Amount="25"/> 
- <Verb_List>
     <Verb_Item Key="1" Execute="RapidOnSite_Pump_AdHoc" Result="OK" 
      Detail="All Pumps►5" /> 
  </Verb_List>

from this string i only want to select Nodes which State is not Idle.

My Code

 string responseFromServer = MY_RESPONSE
     XmlDocument mainxml = new XmlDocument();
    mainxml.LoadXml(responseFromServer);

  XmlNodeList xnList = mainxml .SelectNodes("/Shofar/RapidOnSite_Pump [@State!='Idle']");

But by this code i didnt get requirments. can anyone please help me?

In the chat you show real xml. It contains the namespace which must be taken into account!

mainxml.LoadXml(responseFromServer);

XmlNamespaceManager manager = new XmlNamespaceManager(mainxml.NameTable);
manager.AddNamespace("ns", "http://ShofarNexus.com");

XmlNodeList xnList = mainxml.SelectNodes("/ns:Shofar/ns:RapidOnSite_Pump [@State!='Idle']", manager);

You can use XElement to get your work done, unless you want to stick to XmlDocument.

XElement rootElem = XElement.Load(new StringReader(xmlStr));
var rapidOnSitePumpWhichAreNotIdle = rootElem.Descendants("RapidOnSite_Pump").Where(e => e.Attribute("State").Value != "Idle");

At the end you will get IEnumerable<XElement> which can be iterated over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM