Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Get "value" from an xml file using xpath

I want to print the "value" Computer into my console. but I’m unable to find proper resources as I don’t know the terminology that is needed to search, like nodes, child, values, ecc..

My current code:

XDocument xml = XDocument.Load(Localization);
XElement pattern = xml.XPathSelectElement("/resources/string[@key=\"Example\"]");

Xml:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<resources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <string key="Example">Computer</string>
</resources>

What can I do to print that value?

>Solution :

You are getting an XElement object from xml.XPathSelectElement(). In The XElement class, there is a property called Value which will return the enclosing text (string) within an element.

The following code will print out what you desired:

XDocument xml = XDocument.Load(Localization);
XElement pattern = xml.XPathSelectElement("/resources/string[@key=\"Example\"]");

Console.WriteLine(pattern.Value);

Console output:

Computer

Terminology

XML/HTML can be viewed as a tree of nodes (element) and children of nodes.

enter image description here

Attribution: W3 Schools

  • Document is the parent of Root Element
  • Root Element is a child of Document
  • The ancestors of <head> are <html> and Document (think family tree)
  • The descendants of Document are all the children nodes including nested children
  • Siblings are nodes on the same level. For example, <head> is a sibling to <body>

The XElement class allows you to traverse other nodes that are related to the current node.

XPath allows you to easily traverse the XML tree using a string.

XElement Documentation

https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement?view=net-7.0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading