简体   繁体   English

C# 使用 xpath 从 xml 文件中获取“值”

[英]C# Get "value" from an xml file using xpath

I want to print the "value" Computer into my console.我想将“值” Computer打印到我的控制台中。 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..但我无法找到合适的资源,因为我不知道搜索所需的术语,如节点、子节点、值、ecc..

My current code:我当前的代码:

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

Xml: 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?我该怎么做才能打印该值?

You are getting an XElement object from xml.XPathSelectElement() .您将从xml.XPathSelectElement()获得XElement object。 In The XElement class, there is a property called Value which will return the enclosing text (string) within an element.XElement class 中,有一个名为Value的属性,它将返回元素内的封闭文本(字符串)。

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:控制台 output:

Computer

Terminology术语

XML/HTML can be viewed as a tree of nodes (element) and children of nodes. XML/HTML 可以被视为节点(元素)和节点子节点的树。

在此处输入图像描述

Attribution: W3 Schools归因: W3 学校

  • Document is the parent of Root Element DocumentRoot Element
  • Root Element is a child of Document Root ElementDocument的子元素
  • The ancestors of <head> are <html> and Document (think family tree) <head>的祖先是<html>Document (想想家谱)
  • The descendants of Document are all the children nodes including nested children Document的后代是所有子节点,包括嵌套子节点
  • Siblings are nodes on the same level.兄弟姐妹是同一级别的节点。 For example, <head> is a sibling to <body>例如, <head><body>的兄弟

The XElement class allows you to traverse other nodes that are related to the current node. XElement class 允许您遍历与当前节点相关的其他节点。

XPath allows you to easily traverse the XML tree using a string. XPath 允许您使用字符串轻松遍历 XML 树。

XElement Documentation X元素文档

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

You do not need xpath with xml linq. Use a dictionary to get all key values你不需要xpath和xml linq。使用字典获取所有键值

           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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM