Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing XML in C# XML for specific Content
    text
    copied!<p>I am trying to parse an XML response from a website in C#. The response comes in a format similar to the following:</p> <pre><code>&lt;Company&gt; &lt;Owner&gt;Bob&lt;/Owner&gt; &lt;Contact&gt; &lt;address&gt; -1 Infinite Loop &lt;/address&gt; &lt;phone&gt; &lt;LandLine&gt;(000) 555-5555&lt;/LandLine&gt; &lt;Fax&gt; (000) 555-5556 &lt;/Fax&gt; &lt;/phone&gt; &lt;email&gt; foo@bar.com &lt;/email&gt; &lt;/Contact&gt; &lt;/Company&gt; </code></pre> <p>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:</p> <pre><code>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(); } } } } } } </code></pre> <p>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)</p> <p>Note: the above C# code is not exact, and lacks some checks etc, but it demonstrates my current abysmal disgusting approach</p> <p>What is the best/cleanest way to simply extract the content from those two Elements if they are present? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload