¿Seleccionando nodos XML?

I have a large XML file with a lot of these file nodes:

<File>
  <Component>Main</Component>
  <Path>C:\Logs\Main</Path>
  <FileName>logfile1.log</FileName>
</File>

In my C# program I want to select a node with a certain file name, eg in the above example I would like to select the File node where the FileName is logfile1.log. Is there a way I can do this in my C#, or maybe I need to make the FileName as an attribute for each File node, e.g.:

<File name="logfile1.log">...</File>

Could anybody advise me on the best practise here? Thanks for any help!

preguntado el 08 de noviembre de 11 a las 17:11

3 Respuestas

XPath query would be a good choice for that. You can use xpath to search for either an element name or an attribute name.

algo como:

var doc = new XPathDocument(path);
var xpath = doc.CreateNavigator();

//with element
var node = xpath.SelectSingleNode("//File[FileName='logfile1.log']");

//or with attribute
var node = xpath.SelectSingleNode("//File[@name='logfile1.log']");

Or, if there could be more than one you can use Select to find multiple matches and then iterate them.

var node = xpath.Select("//File...");

respondido 08 nov., 11:22

Using query syntax;

var xml = XDocument.Load("input.xml");
var node = (from file in xml.Descendants("File")
           where (string)file.Element("FileName") == "logfile1.log"
           select file).Single();

Obviously the call to force the query (Single() in this case) should be swapped out to suit your own app.

respondido 08 nov., 11:22

var doc = new XmlDocument();
doc.LoadXml(xml); // or Load(path)
var node = doc.SelectSingleNode("//File/FileName[.='logfile1.log']");

(consulte Selección de XPath por innertext)

or

var doc = XDocument.Load(path);
var node = doc.Elements("Path").FirstOrDefault(e => (string)e.Element("FileName") == "logfile1.log");

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.