我想將“值”列印Computer到我的控制臺中。但我無法找到合適的資源,因為我不知道搜索所需的術語,如節點、子項、值、ecc ..
我當前的代碼:
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>
我能做些什么來列印那個值?
uj5u.com熱心網友回復:
您正在XElement從xml.XPathSelectElement(). 在XElement類中,有一個名為的屬性Value將回傳元素內的封閉文本(字串)。
以下代碼將列印出您想要的內容:
XDocument xml = XDocument.Load(Localization);
XElement pattern = xml.XPathSelectElement("/resources/string[@key=\"Example\"]");
Console.WriteLine(pattern.Value);
控制臺輸出:
Computer
術語
XML/HTML 可以被視為節點(元素)和節點的子節點的樹。

歸屬:W3 學校
Document是父母Root ElementRoot Element是的孩子Document<head>是<html>和的祖先Document(想想家譜)- 的后代
Document是所有子節點,包括嵌套子節點 - 兄弟姐妹是同一級別的節點。例如,
<head>是兄弟姐妹<body>
該類XElement允許您遍歷與當前節點相關的其他節點。
XPath 允許您使用字串輕松遍歷 XML 樹。
XElement 檔案
https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xelement?view=net-7.0
uj5u.com熱心網友回復:
您不需要帶有 xml linq 的 xpath。使用字典獲取所有鍵值
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());
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512778.html
標籤:C#xml路径
