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:
<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.
Attribution: W3 Schools
Documentis the parent ofRoot ElementRoot Elementis a child ofDocument- The ancestors of
<head>are<html>andDocument(think family tree) - The descendants of
Documentare 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
