[英]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命名空间中的类。
按照@MiffTheFox的回答 ,您可以将XPath与LINQ 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.