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.

3 Answers 3

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"];
Sign up to request clarification or add additional context in comments.

4 Comments

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?
@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
If you are getting a null pointer it is because the top level element isn't named 'HistoryResponse'. Element(<Name>) 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.
Ntsc - Thanks, that was exactly it. And thank you all, I have it working now.
0

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.