tags:

views:

791

answers:

3

I have the following XML document

  <MimeType>
     <Extension>.aab</Extension>
     <Value>application/x-authorware-</Value>
  </MimeType>
  <MimeType>
     <Extension>.aam</Extension>
     <Value>application/x-authorware-</Value>
  </MimeType>

The whole document contains about 700 entries, how can I extract a single Mime Type element using XPath and populate it into a strongly typed C# MimeType object?

Thanks

+1  A: 

You use the classes in the System.Xml.XPath namespace.

Tutorials from MSDN

MiffTheFox
+9  A: 

Use XmlDocument.SelectSingleNode.

Example:

XmlDocument doc = new XmlDocument();
doc.Load("yourXmlFileName");
XmlNode node = doc.SelectSingleNode("yourXpath");

Then you can access node.ChildNodes in order to get the values you want (example):

string extension = node.ChildNodes[0].InnerText;
string value = node.ChildNodes[1].InnerText;

And then use those values when constructing your MimeType object.

Edit: Some XPath info.
There are some really good XPath tutorials out there, try here and here. The W3C recommendation itself can be a bit overwhelming.
For your example, you could try using the following XPath to select the first MimeType node in the document (where root is whatever the name of your root element):

string xPath = "root/MimeType[1]"

Hope that helps!

Donut
Donut's snippet sums it all! It's hardly more difficult than that. You may want to check my reply to the the SO posting at http://stackoverflow.com/questions/1440184/how-to-display-value-in-log-file-from-an-xml-file/1440642 for a longer snippet indicative of error conditions, what's returned when not found etc.
mjv
ok I'll give this a go... any chance of getting an XPath example? Sorry to be cheeky?
JL
Yep, added some XPath info (links + simple example) to my answer - hope it helps.
Donut
+2  A: 

The following method should provide a framework for getting the MIME Type here

public MimeType RunXPath(string mimeType)
{
  XmlNode node = _xmlDoc.SelectSingleNode(
    string.Format("//MimeType/Extension[text()="{0}"]/ancestor::MimeType", mimeType));
  foreach(XmlNode node in nodes)
  {
    // Extract the relevant nodes and populate the Mime Type here...
  }

  return ...
}

The trick is to find the MimeType based on the text in the extension, then retrieve the ancestor of MimeType for this match.

Pete OHanlon