tags:

views:

42

answers:

3

I have an XML file full of this:

 <machine id="">
  <application id="">
   <fichier name=""/>
   <fichier name=""/>
   <fichier name=""/>
  </application>
  <application id="">
   <fichier name=""/>
   <fichier name=""/>
   <fichier name=""/>
  </application>
 </machine>

I know the id of machine and application and the name of fichier. Right now, I scan all machine, then once found, scan application and once found, scan fichier. Rather long, so how can I quickly reach the fichier I want?

+1  A: 

XPath

http://www.w3schools.com/XPath/xpath_syntax.asp

Sruly
Ah thanks alot. This is exactly what I was looking for.
Wildhorn
+2  A: 

something like the following should work, assuming you loaded your XML in an XmlDocument called xmlDoc:

// load your XML (you may already have this)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToYourXML);

// construct your XPath
string formattedXPath = string.Format(
    "/machine[@id='{0}']/application[@id='{1}']/fichier[@name='{2}']", 
    machineId, 
    applicationId, 
    fichierName);

// select your node
XmlElement elementFichier = (XmlElement) xmlDoc.SelectSingleNode(formattedXPath)

// if you need the text from this child, use this (text itself is a child node):
string text = elementFichier.FirstChild.Value;

PS: the above uses XPath, there are several tutorials on the Net (as mentioned by another user meanwhile), but if you really want to learn how to work with it, try some of Jenni Tennison's books on XSLT, she's an excellent explainer.

Abel
For some reason, this doesnt return me anything. I get null return on xmldoc.SelectSingleNode
Wildhorn
@Wildhorn: If you get `null`, then either your input is different (i.e., the root is not `/machine`, replace it with the correct path from root or use `//` instead of `/`) or there's a typo in your translation, because the code above, with your input (added attribute values), produces a node for me...
Abel
yeah I figured that I misplaced a '='. Was just a sily typo :)
Wildhorn
A: 

You could do this with LINQ to XML like this:

 var result = from m in xml.Descendants("machine")
             where m.Attribute("id").Value == "1"
              let a = m.Elements("application").Where (x => x.Attribute("id").Value == "3")
              let f = a.Elements("fichier").Where (x => x.Attribute("name").Value == "b")
              select f;
Steve Michelotti