使用 C# 解析 XML 文件? [英] Parsing XML file using C#?

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

问题描述

我是 XML 和 C# 的新手;我试图找到一种方法来有效解析给定的 xml 文件以检索相关数值,基于proj_title"value=heat_run 或任何其他可能的值.例如,计算特定测试运行的持续时间(proj_end val-proj_start val).

I'm new to both XML and C#; I'm trying to find a way to efficiently parse a given xml file to retrieve relevant numerical values, base on the "proj_title" value=heat_run or any other possible values. For example, calculating the duration of a particular test run (proj_end val-proj_start val).

ex.xml:

<proj ID="2">
      <proj_title>heat_run</proj_title>
      <proj_start>100</proj_start>
      <proj_end>200</proj_end>
</proj>

...我们无法按项目 ID 进行搜索,因为此值在每次测试运行中都不是固定的.上面的文件很大:~8mb,有~2000 个标签,名称为 proj_title.有没有一种有效的方法可以首先找到所有带有 proj_title="heat_run" 的标签名称,然后使用 C# 检索此特定 proj_title 的 proj 开始和结束值??

... We can't search by proj ID since this value is not fixed from test run to test run. The above file is huge: ~8mb, and there's ~2000 tags w/ the name proj_title. is there an efficient way to first find all tag names w/ proj_title="heat_run", then to retrieve the proj start and end value for this particular proj_title using C#??

这是我当前的 C# 代码:

Here's my current C# code:

public class parser
{
     public static void Main()
     {
         XmlDocument xmlDoc= new XmlDocument();
         xmlDoc.Load("ex.xml");

         //~2000 tags w/ proj_title
         //any more efficient way to just look for proj_title="heat_run" specifically?
         XmlNodeList heat_run_nodes=xmlDoc.GetElementsByTagName("proj_title");
     }
}    

推荐答案

可以使用XPath查找所有匹配的节点,例如:

You can use XPath to find all nodes that match, for example:

XmlNodeList 匹配 = xmlDoc.SelectNodes("proj[proj_title='heat_run']")

matches 将包含与标准匹配的所有 proj 节点.了解有关 XPath 的更多信息:http://www.w3schools.com/xsl/xpath_syntax.asp

matches will contain all proj nodes that match the critera. Learn more about XPath: http://www.w3schools.com/xsl/xpath_syntax.asp

SelectNodes 上的 MSDN 文档

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

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