[英]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
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
Document
是Root Element
Root Element
is a child of Document
Root Element
是Document
的子元素<head>
are <html>
and Document
(think family tree) <head>
的祖先是<html>
和Document
(想想家谱)Document
are all the children nodes including nested children Document
的后代是所有子节点,包括嵌套子节点<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 树。
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.