简体   繁体   English

如何在C#中获取包含另一个xml节点的节点

[英]how to get the nodes which contain another xml nodes in c#

I have few xml documents. 我有几个xml文件。 and each document has different nodes. 每个文档都有不同的节点。 Only thing common is it has _Header and _Table nodes. 唯一常见的是它具有_Header和_Table节点。 what i want is to get the parent nodes which contain _Header and _Table nodes. 我想要的是获取包含_Header和_Table节点的父节点。

在此处输入图片说明

I want the program to output the following nodes: 我希望程序输出以下节点:

_StatementofNetAssets_T1
_StatementofNetAssets_T2
_StatementofNetAssets_T3

How can I do this? 我怎样才能做到这一点?

XmlDocument xmlDoc=new XmlDocument(); 
string xmlname=Server.MapPath("*.xml").ToString();
xmlDoc.Load(xmlname); 
XmlNodeList    nodeList=xmlDoc.SelectSingleNode("form/Documents").ChildNodes;//get all child nodes
foreach(XmlNode xn in nodeList) 
{ 
  XmlElement xe2=(XmlElement)xn;

  if(xe2.InnerText=="_Header"||xe2.InnerText=="_Table nodes")
  {
    XmlNode xn3=xn.ParentNode; 
    XmlElement xe=(XmlElement)xn3; 
    Console.WriteLine(xe.InnerText);
   }
} 

You could use XDocument class and XPath to quickly parse your documents 您可以使用XDocument类和XPath快速解析您的文档

var elements = XDocument.Load(path).XPathSelectElements("//_Header").Select(q => q.Parent);

You will be needing these namespaces 您将需要这些名称空间

using System.Linq;
using System.Xml.XPath;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM