Hi. I've got to write some code to get data from an XML document and turn it into C# objects. Problem is that the XML document will not always have the same nodes, since it is produced from a web form that people have filled in varying amounts of (which I cannot control since the xml is from a 3rd party resource). For example sometimes the XML document has a <NamePrefix> tag to contain Mr./Mrs./... etc, but if people haven't filled this in on the form it won't. This means that when I call


this will sometimes throw an exception if the <NamePrefix> tag does not exist. The obvious way around this is to write a try-catch block around every such statement in my code, but this would mean about 100 try-catch blocks, which I'm sure would be terrible for performance, let alone readability! Is there another way to solve this problem?

Many thanks.

Recommended Answers

All 3 Replies

If the document is flat then you could enumerate through ChildNodes and process according to what you find.
This might even be more efficient than doing about 100 TagName seaches with selectSingleNode.
[Edit] or maybe not as you will have to have a big block of if then else if ....



will not throw an exception in this case it will simply return null so try something like:

XmlNode someNode = doc.SelectSingleNode("SomeNode");
if(someNode != null)
  //Do something

Thanks atomic_age that's what I did in the end

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.