在 C# 中很新,所以試圖學習 xml 序列化。我有一個如下的 xml 設定:
<Guy>
<Name>
<Root>
<Entry>
<Favorite> his favorite food is sushi </Favorite>
</Entry>
</Root>
</Name>
</Guy>
我需要選擇“最喜歡的”標簽并回傳“他最喜歡的食物是壽司”。在 C# 中解決這個問題的最簡單方法是什么?可以使用 XDocument 和 LINQ 擴展嗎?
uj5u.com熱心網友回復:
string xml = @"
<Guy>
<Name>
<Root>
<Entry>
<Favorite> his favorite food is sushi </Favorite>
</Entry>
</Root>
</Name>
</Guy>";
var doc = XDocument.Parse(xml);
Console.WriteLine(doc.Descendants("Favorite").First().Value);
// or
foreach(var item in doc.Descendants("Favorite").Select(e => e.Value))
{
Console.WriteLine(item);
}
https://dotnetfiddle.net/Iagop5
uj5u.com熱心網友回復:
您可以使用 XPathNavigator 嘗試這種方法:
public static string GetAttribute(string xml, string nodeName) {
StringReader stringReader = new StringReader(xml);
XPathDocument doc = new XPathDocument(stringReader);
XPathNavigator xNav = doc.CreateNavigator();
XPathNavigator node = xNav.SelectSingleNode("//" nodeName);
return node != null ? node.InnerXml : string.Empty;
}
這是一個參考:https ://docs.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathnavigator.selectsinglenode?view=net-6.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/497322.html
上一篇:如何將字串具體化為實際型別?
