I've got a project where I'm currently implementing support for reading values from an XML file via an arbitrary/user-defined path within the document's keys.
For example, if the document looks like this:
<information>
<machine>
<foo></foo>
<name>
test machine
</name>
<bar>spam</bar>
</machine>
</information>
then the user might want to retrieve the value from the name
key in information/machine
.
Is there a way using XDocument
/XPath
that I can look up the values the user wants without knowing/coding in the schema for the document?
My initial thought was working through the document with a form of recursive function utilizing XElement
items, but I feel like there ought to be a simpler/cleaner solution that doesn't require me rolling my own lookup code.
I also tried something along these lines
var doc = XDocument.Load("C:\Path\to\XML\file.xml");
// Split the parent keys string
XElement elem = doc.Root.XPathSelectElement("path/to/key");
if (elem != null && elem.Attribute("wantedKeyName") != null)
replace = elem.Attribute("wantedKeyName").Value;
but elem
is always null. I'm assuming there's a problem with the way I'm defining my path or utilizing XPathSelectElement, but I haven't worked it out yet.