0

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!

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

something like:

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...");

Comments

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

(see XPath selection by innertext)

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.