簡體   English   中英

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

[英]Extracting an XML element from an XML file using XPath

我有以下XML文檔:

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

整個文件包含約700個條目。 如何使用XPath提取單個MimeType元素並將其填充到強類型的C# MimeType對象中?

使用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]"

希望有所幫助!

以下方法應提供在此處獲取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的祖先。

您使用System.Xml.XPath命名空間中的類。

來自MSDN的教程

按照@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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM