[英]Simplest way to parse the element in this XML C#
Pretty new at C# so trying to learn xml serialization.在 C# 中很新,所以试图学习 xml 序列化。 I have an xml setup like the following:
我有一个如下的 xml 设置:
<Guy>
<Name>
<Root>
<Entry>
<Favorite> his favorite food is sushi </Favorite>
</Entry>
</Root>
</Name>
</Guy>
I need to select the "Favorite" tags and return the "his favorite food is sushi".我需要选择“最喜欢的”标签并返回“他最喜欢的食物是寿司”。 What is the simplest way to go about this in C#?
在 C# 中解决这个问题的最简单方法是什么? Can XDocument and LINQ extensions be used?
可以使用 XDocument 和 LINQ 扩展吗?
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
https://dotnetfiddle.net/Iagop5
You can try this approach using XPathNavigator:您可以使用 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;
}
Here's a reference: https://docs.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathnavigator.selectsinglenode?view=net-6.0这是一个参考: https ://docs.microsoft.com/en-us/dotnet/api/system.xml.xpath.xpathnavigator.selectsinglenode?view=net-6.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.