This is the XML I’m trying to parse. I’m having trouble parsing the entry elements and getting the different values within them. Usually I can specify the element that I’m trying to get at and extract the value from it. However, this time the elements I’m targeting all have the same name.
<?xml version="1.0" encoding="UTF-8"?>
<response id="-46056350:133f0f5eff1:54e3">
<userdata>
<account>
<account>23408234</account>
</account>
<disabled>false</disabled>
<resetpassword>false</resetpassword>
<userprofile>
<entry>
<name>primaryMiddleInitial</name>
<value/>
</entry>
<entry>
<name>primaryLastName</name>
<value>chen</value>
</entry>
<entry>
<name>login_id</name>
<value>Negative</value>
</entry>
<entry>
<name>zip</name>
<value/>
</entry>
<entry>
<name>primaryFirstName</name>
<value>eric</value>
</entry>
<entry>
<name>emailAddress1</name>
<value>ECHEN57@GMAIL.COM</value>
</entry>
</userprofile>
</userdata>
<error>Success</error>
</response>
And this is my attempt at parsing it.
public static MemberViewModel ParseMemberXML(string xml)
{
XDocument data = XDocument.Parse(xml);
return (from c in data.Descendants("userdata")
select new MemberViewModel()
{
Account = c.Element("account").Element("account").Value,
PrimaryFirstName = c.Element("userprofile").Element("entry").Element("value").Value
PrimaryLastName
PrimaryMiddleInitial
LoginID
}).ToList().ElementAt(0);
}
How would I parse this?
Your best bet is to iterate over the “entry” elements and assign their values to fields of the MemberViewModel object as you discover them.
Something like this:
You could instead use XPath expressions to select individual elements by specifying their parentage path, but frankly I think the foreach loop is more manageable.