How do I loop through multiple instance of an XmlNode

  • Thread starter Thread starter Thirsty Traveler
  • Start date Start date
T

Thirsty Traveler

Given the XML sampe below, how would I loop through all of the borrowers in
the XML document in order to process the attributes:

<REQUEST_GROUP MISMOVersionID="2.1.1" InternalAccountIdentifier="">

<REQUEST RequestDatetime="2003-12-08T09:37:28>

- <REQUEST_DATA>

<BORROWER _FirstName="BNUM1" _LastName="LNAME1" />

- <BORROWER _FirstName="BNUM2" _LastName="LNAME2" />

</REQUEST_DATA>

</REQUEST>

</REQUEST_GROUP>



// In this example, I would like to process the BORROWER attributes for both
borrowers... how?

node = xml.SelectSingleNode("REQUEST_GROUP/REQUEST/REQUEST_DATA/BORROWER",
nsMgr);


if (node != null) { fn = node.Attributes["_FirstName"].Value; }

if (node != null) { ln = node.Attributes["_LastName"].Value; }
 
Hi Thirsty,

I assume you meant to process both BORROWER elements (as they not
attributes, but elements). Following is a modified version of your code

XmlNodeList nodeList =
xml.SelectNodes("REQUEST_GROUP/REQUEST/REQUEST_DATA/BORROWER");

foreach (XmlNode node in nodeList)
{
String fn = node.Attributes["_FirstName"].Value;
String ln = node.Attributes["_LastName"].Value;
MessageBox.Show(fn);
}

Hope this helps!

Y. Sivaram
 
I assume you meant to process both BORROWER elements (as they not attributes, but elements). Following is a modified
version of your code

XmlNodeList nodeList = xml.SelectNodes("REQUEST_GROUP/REQUEST/REQUEST_DATA/BORROWER");

foreach (XmlNode node in nodeList)
{
String fn = node.Attributes["_FirstName"].Value;
String ln = node.Attributes["_LastName"].Value;
MessageBox.Show(fn);
}

This would cause a problem if the required attribute was not present since Attributes["_FirstName"] would return null.
You can get around this problem by slightly modifying the XPath query to pull back only those nodes that have the
required attribute:

***
XmlNodeList nodeList =
xml.SelectNodes("REQUEST_GROUP/REQUEST/REQUEST_DATA/BORROWER[@_FirstName]");
***

Of course if the attribute is required in your schema then this makes no difference so either version will work in that
case.
Hope this helps,

Mike


- Microsoft Visual Basic MVP -
E-Mail: (e-mail address removed)
WWW: Http://EDais.mvps.org/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top