C# 使用XPath从XML文件中提取XML元素

C# 使用XPath从XML文件中提取XML元素,c#,xml,xpath,C#,Xml,Xpath,我有以下XML文档: <MimeType> <Extension>.aab</Extension> <Value>application/x-authorware-</Value> </MimeType> <MimeType> <Extension>.aam</Extension> <Value>application/x-a

我有以下XML文档:

  <MimeType>
     <Extension>.aab</Extension>
     <Value>application/x-authorware-</Value>
  </MimeType>
  <MimeType>
     <Extension>.aam</Extension>
     <Value>application/x-authorware-</Value>
  </MimeType>

.aab
应用程序/x-authorware-
嗯
应用程序/x-authorware-

整个文档包含大约700个条目。如何使用XPath提取单个
MimeType
元素,并将其填充到强类型C#
MimeType
对象中?

使用命名空间中的类

使用

例如:

XmlDocument doc = new XmlDocument();
doc.Load("yourXmlFileName");
XmlNode node = doc.SelectSingleNode("yourXpath");
然后,您可以访问
node.ChildNodes
,以获取所需的值(示例):

然后在构造MimeType对象时使用这些值

编辑:一些XPath信息。
有一些非常好的XPath教程,请尝试使用。这个问题本身可能会有点难以克服。
例如,您可以尝试使用以下XPath选择文档中的第一个
MimeType
节点(其中
root
是根元素的名称):


希望有帮助

下面的方法应该提供一个获取MIME类型的框架

public MimeType RunXPath(string mimeType)
{
  XmlNode node = _xmlDoc.SelectSingleNode(
    string.Format("//MimeType/Extension[text()="{0}"]/ancestor::MimeType", mimeType));
  foreach(XmlNode node in nodes)
  {
    // Extract the relevant nodes and populate the Mime Type here...
  }

  return ...
}
诀窍是根据扩展名中的文本查找MimeType,然后检索此匹配的MimeType的祖先。

接下来,您可以使用XPathLINQ to XML。下面是一个基于示例数据的示例

1)首先,您需要的名称空间:

using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
2)将XML文档加载到
XElement

XElement rootElement = XElement.Parse(xml);
3)定义XPath位置路径:

// For example, to locate the 'MimeType' element whose 'Extension'
// child element has the value '.aam':
//
//     ./MimeType[Extension='.aam']

string extension = ".aam";
string locationPath = String.Format("./MimeType[Extension='{0}']", extension);
4)将位置路径传递到
XPathSelectElement()
以选择感兴趣的元素:

XElement selectedElement = rootElement.XPathSelectElement(locationPath);
5)最后,提取与扩展相关联的MimeType值:

var mimeType = (string)selectedElement.Element("Value");

您是否被迫不使用.NET3.5?如果您可以使用.NET3.5,我会使用XDocument和LINQtoXML,您会发现它比XPath更简单。不一定。最好将两者结合使用:是的,强制进入.NET2角落。甜甜圈的代码片段将其全部加起来!没有比这更难的了。你可能想查看我对SO发帖的回复,以获取指示错误条件的更长片段、未找到时返回的内容等。好的,我会尝试一下。。。有没有可能得到一个XPath示例?抱歉这么厚颜无耻?是的,在我的答案中添加了一些XPath信息(链接+简单示例)-希望能有所帮助。
XElement selectedElement = rootElement.XPathSelectElement(locationPath);
var mimeType = (string)selectedElement.Element("Value");