How to check if XML node exists with C#

I need to create a try catch so that if the nodes dont exist we can trace it

 

foreach (XmlElement node in root.ChildNodes)
{
OrderType nodeOrderType = new OrderType();
nodeOrderType.id = node.Attributes["id"].Value;
nodeOrderType.value = node.Attributes["value"].Value;
OrderTypes.Add(nodeOrderType);
}

 

this is where i read in the data i need from the xml Ordertype is my object that I return. the person I am passing to has requested that i insert try catches so we can log the errors. I think a simple way may be to just check if the values are null.

 

but say some person wrote the xml file and made an error how can i check and log it so that it says hey this is incorrect syntax, we are lost.

First off, you should define an XSD (XML Schema Definition) that defines the exact XML document that will be exchanged between your two applications.  I assume these applications are two disparate and/or non-collocated applications.  If not, you should not be using XML to exchange information between your applications.  And to be honest even if your applications are disparate and/or non-collocated, you should really use JSON instead of XML for information exchange.  XML is a bad format for two reasons.  One, the verbosity of XML creates unnecessary overhead for information exchange.  Two, XML is a hierarchical document specification not an Object specification so mapping XML to objects is not always clean.

But if you are going to use XML, using an XSD to define your message exchange contract is the way to go.  Inside the schema you can define what fields are required and optional, the types of each of your fields, and if you verify all of your XML messages against the schema, you will not run into the issue of an expected field missing, null, or the wrong type.

To use this approach the first thing you need to do is create an XSD.  This is actually fairly easy, and if you do not want to do it by hand, if you have a sample XML message, you can quickly and easily generate an XSD from the XML message using this website:

http://www.freeformatter.com/xsd-generator.html

The next thing you have to do is generate C# objects that represent your XSD.  Visual Studio has a tool that will do this for you.  It is called xsd.exe.  It can be a little difficult to find.  It is located here:   C:\Program Files(x86)\Microsoft SDKs\Windows\v7.0A\Bin.  If you do not have the v7.0A directory just drill down to the above listed Windows directory and find whatever version you have and look in that version’s Bin directory.

Put the above directory in your path, open up a command prompt, navigate to where your XSD file is located, and type this:

xsd <your xsd> /c /l:cs /n:<whatever namespace you want>  /out:<output directory where you want the classes to go>

E.g.,

xsd order.xsd /c /l:cs /n:xmltest /out:xml

Now take the generate class(es) and copy them into your project.  Now you can consume and create XML messages using C# classes.  And if you want to see if a particular field from an XML document is present you can just use the getters and setters of the class and check for yourself.

I will include sample code for how to do this below:

Sample XSD:

http://pastebin.com/ExjKz8Yt

 

Sample class generated from XSD.exe:

http://pastebin.com/m2gXtLp2

How to deserialize and serialize XML messages to and from C# objects—using the above generated class as an example:

http://pastebin.com/HXkw2hJi

 

I have no choice but to use xml.

 

also you didnt really answer my question you just suggested alternatives to do what i already did.

 

I want to know the methods (if they exist) that can check if the xml is formatted correctly since some person in customer support is going to be creating these documents (our client) On our end we have a log manager and i want to be able to check the following

is the format correct

and if the format is correct do they have the correct childnodes

 

if these should fail we need to log it so we can fix it quicker

 

I may just be able to put a try catch around this

 XmlDocument doc = new XmlDocument();

and that will solve the first issue. but the next one is a little tricky since i dont know all the methods that System.xml gives you

I guess I did not clarify my answer.  When you use XmlDocument, the only thing that it does for you is ensure that the XML String, Reader, or stream, you pass to it is a legitimate XML document.  XML by its nature is freeform, as long as you conform to the rules of XML, you can create any hierarchical structured document you want.

The freeform nature is where the problem arises.  Usually you use XmlDocument to make minor changes to existing XML documents or to retrieve known elements.  It is usually not used for extensive processing of XML.  Using XmlDocument to build a generified method to process any XML document and determine which fields are present and which are not, which fields have values and which do not, would be very difficult and more than likely result in brittle code.

A couple of years back, I took over an application where the developers did pretty much what you are trying to do.  The application received XML messages over a socket, and they used XmlDocument to process the incoming XML.  The developers coded the xml processing based on the message they were currently receiving.  It was very convoluted and hacky code, but it did work.  However, a problem arose when a second source for the XML messages was added.  Now the XML processing code would throw null argument exceptions, and because of the nature of code based on XmlDocument, trying to debug these issues was tedious.  To solve this problem, I did exactly what I suggested you do.  After I made the changes, several new sources sending XML documents were added and there are no problems processing them.

It sounds like you have not determined the exact format of what your XML document(s) will be.  This is something that you need to work out with your customer.  You both need to agree on they exact format of your XML document(s).  And the best way to do this is create an XSD for each of your XML documents.  Having partial matching XML types is a recipe for disaster, unless you are going to be doing document transformation using XSLT.  But even then, the exact format of your incoming document needs to be determined.

If you are still dead set on using XmlDocument, you can and MSDN tells you exactly what methods to use to parse and process an XML document:

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

My fix has been a lot simpler than you suggested and I am able to catch most errors with the try catch I have.

XmlDocument doc = new XmlDocument();

try
{
doc.Load(pathFilename);
XmlElement root = doc.DocumentElement;

foreach (XmlElement node in root.ChildNodes)
{
OrderType nodeOrderType = new OrderType();
nodeOrderType.id = node.Attributes["id"].Value;
nodeOrderType.value = node.Attributes["value"].Value;
OrderTypes.Add(nodeOrderType);
}
}
catch (Exception ex)
{
if(ex is XmlException)
{
LogManager.LogServerError("Problem in XML", ex);
}
else
{
LogManager.LogServerError("Not an XML issue", ex);
}
}

 

I am unable to create a situation that classifies as not an XML exception. I am now wondering what some person could do the document to have it not come up as an XMLexception.

also I am new here. am i pasting code incorrectly? It looks fine in editor but once i save it goes back to a wall of text..