C#和XPath - 如何查询 [英] C# and XPath - how to query

查看:201
本文介绍了C#和XPath - 如何查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,它具有以下结构:

 <的mediawiki ...> 
<&SITEINFO GT; ...< / SITEINFO>
<网页>
<标题>在标题< /标题>
<&ID GT; 42℃; / ID>

< /页> $ B $ ...更多页面项目...
< /的mediawiki>



我红了一下有关XPath查询,并写了下面的代码:

  _xmlArticlesDocument =新的XmlDocument(); 
_xmlArticlesDocument.Load(xmlArticlesFileName);

现在我想要得到与给定的ID子元素页面元素一握。所以我写了:

  XmlNode的节点= _xmlArticlesDocument.DocumentElement.SelectSingleNode 
(//链接到MediaWiki /页[ID = + id.ToString()+]);



但节点总是空。我尝试了好几种querys,包括网页/ ID,网页,/页,//页来获得的任何的,但节点始终为空。我已经通过快速检查检查_xmlArticlesDocument变量,它包含正确的XML文件与预期结构。



在我看来,我已经错过了一些非常基本的,但不知道是什么。也许有人在这里有一个想法?



在提前,
弗兰克


解决方案<谢谢/ DIV>

查询看起来正确你到目前为止我们展示的基础上。不过我怀疑behin的...MediaWiki的元素存在的xmlns =...属性吧?



这会是什么绊倒您我怀疑。你需要这样的代码: -

 的XmlNamespaceManager nsmgr =新的XmlNamespaceManager(_xmlArticlesDocument.NameTable); 
nsmgr.AddNamespace(A,重命名空间 - 在他们-的xmlns属性);
XmlNode的页= _xmlArticlesDocument.SelectSingleNode(的String.Format(//一:页[ID = {0}],ID),nsmgr);


I have an XML-File, which has the following structure:

<mediawiki ...>
  <siteinfo>...</siteinfo>
  <page>
    <title>The Title</title>
    <id>42</id>
    ...
  </page>
  ... more page items ...
</mediawiki>

I red a bit about XPath-Query and wrote the following code:

_xmlArticlesDocument = new XmlDocument();
_xmlArticlesDocument.Load(xmlArticlesFileName);

Now I want to get a grip on a page Element with a given id-Subelement. So I wrote:

XmlNode node = _xmlArticlesDocument.DocumentElement.SelectSingleNode
               ("//mediawiki/page[id=" + id.ToString() + "]");

but node is always null. I have tried several querys, including "page/id", "page", "/page", "//page" to get anything, but node is always null. I have checked via quick inspection the _xmlArticlesDocument variable and it contains the correct XML-file with the expected structure.

It seems to me, that I have missed something very basic, but have no idea what. Maybe someone here has an idea?

Thanks in advance, Frank

解决方案

The query looks right on the basis of what you shown us so far. However I suspect behin the "..." on the mediawiki element there is a xmlns="...." attribute right?

That'll be what is tripping you up I suspect. You will need code like this:-

 XmlNamespaceManager nsmgr = new XmlNamespaceManager(_xmlArticlesDocument.NameTable);
 nsmgr.AddNamespace("a", "the-namespace-in-them-xmlns-attribute");
 XmlNode page = _xmlArticlesDocument.SelectSingleNode(String.Format("//a:page[id={0}]", id), nsmgr);

这篇关于C#和XPath - 如何查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆