XML parse

Experiences, small talk, and other automation gossip.
NewLearner
Posts: 29
Joined: Wed Jan 15, 2014 3:32 pm

XML parse

Post by NewLearner » Mon Jun 01, 2015 2:05 pm

Hi,
my window based application one of field shows xml API response, so i captured as value and stored in a variable like $xmlresponse

$xmlresponse="<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<kmsgresponse><result status='true'/><body><orderNo>38</orderNo><fileRef>39D0C6018AB1000090EA0002</fileRef></body></kmsgresponse>"

how to parse this xml variable into indivdual tag variable...

can i store this $xmlresponse value in to some xml file order.xml then use parsing or is it possible to take tags out from this variable $xmlresponse itself

Thanks in Advance

NewLearner
Posts: 29
Joined: Wed Jan 15, 2014 3:32 pm

Re: XML parse

Post by NewLearner » Mon Jun 01, 2015 3:49 pm

Hi
I just created a function xmltag=$xmlresponse and findxmltag = "orderNo"

public void funcGettab(string xmltag, string findxmltag)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmltag);
XmlNodeList nodeList = xmldoc.GetElementsByTagName(findxmltag);
findxmltagvalue=string.Empty;
foreach (XmlNode node in nodeList)
{
findxmltagvalue = node.InnerText;
}
}

Result : 38
If you have any other optimized way pls let me know

Thank you

CookieMonster
Certified Professional
Certified Professional
Posts: 74
Joined: Mon Aug 14, 2006 7:17 pm
Location: CH

Re: XML parse

Post by CookieMonster » Tue Jun 02, 2015 5:50 pm

Hi NewLearner,

you can do it just a bit more sophisticated. You can use XPath or Regex, then you have a bit more flexibility with the validation of the result.

For e.g.

Code: Select all


public void ValidateXml(string xmlDocument, string xPath, string expectedValue)
{
XDocument xDocument = XDocument.Parse(xmlDocument);			
XPathNavigator xPathNavigator = xDocument.CreateNavigator();
XPathNodeIterator nodeIterator = xPathNavigator.Select(xPath);

if(nodeIterator.Count > 0)
{
  while(nodeIterator.MoveNext())
  {
    //do something.
  }
}

Validate.AreEqual(nodeContent, expectedValues,"Your message");
or
Validate.AreEqual(new RegEx(nodeContent, expectedValues), "Your message");

Cheers
Dan