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

8

I have the following XML document:

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

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

2
你是否被迫不能使用.NET 3.5?如果可以使用.NET 3.5,我会使用XDocument和Linq to Xml,你会发现它比XPath更简单。 - David Basarab
不一定。最好使用两者的组合:https://dev59.com/q0jSa4cB1Zd3GeqPJvHL - Ryall
被迫陷入 .NET 2 的困境。 - JL.
4个回答

15
使用 XmlDocument.SelectSingleNode
示例:
XmlDocument doc = new XmlDocument();
doc.Load("yourXmlFileName");
XmlNode node = doc.SelectSingleNode("yourXpath");

然后,您可以访问node.ChildNodes以获取所需的值(例如):

string extension = node.ChildNodes[0].InnerText;
string value = node.ChildNodes[1].InnerText;

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

编辑:一些XPath信息。
有一些非常好的XPath教程,可以尝试这里这里W3C推荐本身可能有点令人不知所措。
对于您的示例,您可以尝试使用以下XPath选择文档中的第一个MimeType节点(其中root是您的根元素的名称):

string xPath = "root/MimeType[1]"

希望有所帮助!

Donut的代码片段概括了一切!它几乎没有比那更难了。你可能想要查看我在http://stackoverflow.com/questions/1440184/how-to-display-value-in-log-file-from-an-xml-file/1440642上对SO帖子的回复,其中包含更长的代码片段,指示错误条件,以及未找到时返回的内容等。 - mjv
好的,我来试一下...有没有可能给一个XPath的例子?不好意思这么直接问。 - JL.
是的,我在我的回答中添加了一些XPath信息(链接+简单示例)-希望它有所帮助。 - Donut

2
以下方法应该提供一个获取 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的祖先节点。

2

继续@MiffTheFox的答案,你可以使用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");

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接