Home > other >  C# Get "value" from an xml file using xpath
C# Get "value" from an xml file using xpath

Time:10-07

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?

CodePudding user response:

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

CodePudding user response:

You do not need xpath with xml linq. Use a dictionary to get all key values

           XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string, string> dict = doc.Descendants("string")
                .GroupBy(x => (string)x.Attribute("key"), y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
  • Related