[英]Select a child node in XML with specific name using C#
I am trying to find a child element with tag name Reason. 我正在尝试查找标签名为Reason的子元素。 I have XML doc that is basically contains bunch of elements with Entity name. 我有XML doc,它基本上包含一堆带有实体名称的元素。 Reason tag is somewhere inside of Entity(along with other elements). Reason标记位于Entity内部(以及其他元素)。
void IParseResponse.ParseResponseData(XmlDocument responseDocument)
{
List<string> reasons = new List<string>();
var reasonValue = "";
var entityList = responseDocument.GetElementsByTagName("Entity");
if (entityList != null)
{
foreach (XmlNode reason in entityList)
{
reasonValue = //look into current Entity element, find Reason in it and get it's inner text.
reasons.Add(reasonValue);
}
}
}
This is location of Reason element. 这是Reason元素的位置。
<Entity>
<WatchList>
<Match ID="1">
<MatchDetails>
<Reason>
Does anybody have experience with this? 有没有人有这方面的经验?
Here's how you can get all the Reason
elements. 以下是如何获得所有Reason
元素的方法。
var xml = "<Entity> <WatchList><Match ID=\"1\"><MatchDetails><Reason>asdasd</Reason></MatchDetails></Match></WatchList></Entity>";
var x = XDocument.Parse(xml);
var reasons = x.Descendants("Reason").ToList();
foreach (var reason in reasons)
{
Console.WriteLine(reason.Value);
}
If you give us a more complete example of your XML I can improve the answer. 如果您给我们一个更完整的XML示例,我可以改进答案。
Edit: 编辑:
If you want to use XmlDocument instead you could do this: 如果你想使用XmlDocument,你可以这样做:
XmlNodeList nodes = responseDocument.GetElementsByTagName("Reason");
for (int i = 0; i < nodes.Count; i++)
{
Console.WriteLine(nodes[i].InnerText);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.