0

Part of my MVC app is a controller action method that POSTs data to a web service and receives an XML response. I have figured out how to get the response into an XDocument but now I need to go through the info and get some of the node values. I have been researching, and the closest option I can find it to use XPath.

I am wondering if this is the best way to go, or if you suggest another way. The XML I am working with will look something like:

<HistoryResponse>
  <ResponseType>resultsList</ResponseType>
  <Matches>0</Matches>
  <SessionID>75803234r23df3de</SessionID>
  <RecStart>0</RecStart>
  <ClientCode></ClientCode>
  <Results></Results>
</HistoryResponse>

I need to go through, grab the Matches and SessionID and put the values into variables.

Thanks.

BattlFrog
  • 3,370
  • 8
  • 56
  • 86

3 Answers3

1

You can convert your xml to dictionary

var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(fileName)
var dict = xDoc.Element("HistoryResponse")
               .Elements()
               .ToDictionary(e => e.Name.LocalName, e => e.Value);

and use as

string sessionID = dict["SessionID"];
L.B
  • 114,136
  • 19
  • 178
  • 224
  • I like this idea, but I am getting a null exception error on the second part (var dictionary = blah blah) while running in debugger. Do I need to do somekind of IDictionary?something> dict = new so on and so forth? – BattlFrog Dec 12 '12 at 20:06
  • @teahou No you don't need anything special. I tested above code with the xml string you posted and it works. If you load your xml from file, don't forget to use `XDocument.Load` – L.B Dec 12 '12 at 20:10
  • If you are getting a null pointer it is because the top level element isn't named 'HistoryResponse'. Element() returns null if it can't find the element. Elements() returns an empty enumeration if nothing matches and ToDictionary returns an empty Dictionary if the source is empty. – NtscCobalt Dec 12 '12 at 20:11
  • 1
    Ntsc - Thanks, that was exactly it. And thank you all, I have it working now. – BattlFrog Dec 12 '12 at 20:26
0

Use LINQtoXML. (you need to import the namespace System.XML.Linq)

string filePath = Server.MapPath(@"../YourFileLocation/somexml.xml");

//you can load the XML from file/stream /string etc...

XElement elem = XElement.Load(filePath);
if (elem != null)
{
   string sessionId=elem.Element("SessionID").Value;
   string matches=elem.Element("Matches").Value;
}

If you are getting the XML in a string, you can load that to your XElement using Parse method.

string xml = "<HistoryResponse><Item>XML Item A</Item></HistoryResponse>";
XElement elem = XElement.Parse(xml);
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

That would definitely work with an XPath expression. Check out how to use XPath with XDocument? for info on how to do it.

Community
  • 1
  • 1
Peter
  • 171
  • 4