How to read specific value from the XMLNode List in C#

BeUnique 2,332 Reputation points
2023-06-15T12:54:04.09+00:00

I am reading XML file which contains large data. The element attributes contains many child fields.

I Just want to know, how to get the specific child fields from the XMLNode list.

below is my sample code and data.

<Employee EmpId="23817348328">
	<Address1>
		<AddressNames>
			<AddressName>USA-STATE1</AddressName>
		</AddressNames>
		<AddressType>ADDRESS1</AddressType>
	</Address1>
	<Address2>
		<AddressNames>
			<AddressName>CANADA-STATE9</AddressName>
		</AddressNames>
		<AddressType>ADDRESS2</AddressType>
	</Address2>
</Employee>

i want to get Address1 and Address2 values from the XMLNodes.

output for Address1 ==> USA-STATE1

output for Address2 ==> CANADA-STATE9

below is my code for xml nodes.

 XmlNodeList EmpNodes = xmlDoc.SelectNodes("//Employee");
foreach (XmlNode EmpNode in EmpNodes)
                    {
                        long EmpId = long.Parse(EmpNode.Attributes["EmpId"].Value);
					string Address1 = ????
					string Address2 = ????

					}

shall i consider string Address1 = documentNode.FirstChild.FirstChild.FirstChild.InnerText;

is that correct way to get address value...?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-06-15T17:14:24.7366667+00:00

    For example:

    string Address1 = EmpNode.SelectSingleNode( "Address1/AddressNames/AddressName" )?.InnerText;
    string Address2 = EmpNode.SelectSingleNode( "Address2/AddressNames/AddressName" )?.InnerText;
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.