I am trying to parse an XML response from a website in C#. The response comes in a format similar to the following:
<Company>
<Owner>Bob</Owner>
<Contact>
<address> -1 Infinite Loop </address>
<phone>
<LandLine>(000) 555-5555</LandLine>
<Fax> (000) 555-5556 </Fax>
</phone>
<email> [email protected] </email>
</Contact>
</Company>
The only information I want is the LandLine and Fax numbers. However my current approach seems really really poor quality. Essentially it is a bunch of nested while loops and checks to the Element name then reading the Content when I found the right Element. I am using something like the listing below:
XmlReader xml = XmlReader.Create(websiteResultStream, xmlSettings);
while(xml.Read()){
if(xml.NodeType == XmlNodeType.Element){
if(xml.Name.ToString() == "Phone"){
while(xml.Read()) {
if(xml.NodeType == XmlNodeType.Element) {
if(xml.Name.ToString() == "LandLine"){
xml.MoveToContent();
xml.ReadContentAsString();
}
if(xml.Name.ToString() == "Fax"){
xml.MoveToContent();
xml.ReadContentAsString();
}
}
}
}
}
}
I am newer to XML/C#, but the above method just screams bad code! I want to ensure that if the structure changes (i.e. there are addition phone number types like "mobile") that the code is robust (hence the additional while loops)
Note: the above C# code is not exact, and lacks some checks etc, but it demonstrates my current abysmal disgusting approach
What is the best/cleanest way to simply extract the content from those two Elements if they are present?