查询 XML 文件? [英] Querying XML file?

查看:24
本文介绍了查询 XML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相对较小的 xml 文件

I have a relatively small xml file

<g>
  <page no="1" href="page1.xml" >        
      <pic src="20100101001.jpg">1</pic>
      <pic src="20100101002.jpg">2</pic>
      <pic src="20100101003.jpg">3</pic>           
  </page>
  <page no="2" href="page2.xml" >        
      <pic src="20100101011.jpg">1</pic>
      <pic src="20100101012.jpg">2</pic>
      <pic src="20100101013.jpg">3</pic>            
  </page>
  <page no="3" href="page3.xml" >       
      <pic src="20100101021.jpg">1</pic>
      <pic src="20100101022.jpg">2</pic>
      <pic src="20100101023.jpg">3</pic>            
  </page>  
</g>

我想在一个win窗体上有三个按钮(第1页、第2页、第3页),当点击它们时,它们会在三个图片框中加载相关的3张图片(三张图片在xml文件中的同一页面下).

I want to have three buttons (page1,page 2,page 3) on a win form that when clicked they load the relevant 3 pictures in three pictures box(the three pictures are under the same page in the xml file).

我需要一些类似从 xml 中选择页面 = X"之类的东西

I need something that does something like "select from xml where page = X"

我知道我可以使用 xpath(/other xml objects) 或 treeview 对象来执行此操作...但我对这些对象中的任何一个都不太了解,而且我当然无法说出其优缺点每个...

I know that I can do this using xpath(/other xml objects) or a treeview object... but I don't know much about any of those object, and I certainly can't tell the pros and cons of each...

所以我需要你的帮助:)谢谢阿萨夫

So I need your help :) Thanks Asaf

推荐答案

这里是一个涉及 XPathDocument 和 XPath 的解决方案.这在内存方面比使用 Linq (XDocument) 或 XmlDocument 更轻量级,因为它不会在内存中构建 DOM.对于小文件,这通常无关紧要,但 XPathDocument 在大输入时会快得多.

Here is a solution involving XPathDocument and XPath. This is more light-weight regarding memory than using Linq (XDocument) or XmlDocument because it doesn't build up a DOM in memory. For small files this usually does not matter but XPathDocument will be much faster on large input.

string page = "page1.xml";
XPathDocument xdoc = new XPathDocument(@"C:\tmp\smpl6.xml");

XPathNodeIterator result = xdoc.CreateNavigator()
    .Select(string.Format("/g/page[@href = '{0}']/pic/@src", page));

foreach (XPathNavigator item in result)
{
    Trace.WriteLine(item.Value);
}

您可以轻松更改该 XPath 表达式,例如按页码过滤:

You can change that XPath expression easily, e.g. to filter by the page number:

int pageNo = 2;
XPathNodeIterator result = xdoc.CreateNavigator()
    .Select(string.Format("/g/page[@no = '{0}']/pic/@src", pageNo));    

这篇关于查询 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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