c# - 在 C# 中使用 XPath 表达式读取 XML 文件

标签 c# xml xpath xmldocument

我当前在使用 XPath 表达式读取 XML 文件时遇到问题。我使用了 XmlDocument 类。当我尝试从 XML 中读取特定节点时,我得到一个空列表。我试图读取的节点是 ProductionRequest 下面的 ID。

这是我尝试读取的 XML 文件:

<?xml version="1.0" encoding="iso-8859-1"?>
<ProductionSchedule xmlns="http://www.wbf.org/xml/b2mml-v02"> 
  <ID>00000020000000</ID>
  <Location>
   <EquipmentID>8283</EquipmentID>
   <EquipmentElementLevel>Site</EquipmentElementLevel>
  <Location>
   <EquipmentID>0</EquipmentID>
   <EquipmentElementLevel>Area</EquipmentElementLevel>
   </Location>
  </Location>
 <ProductionRequest>
    <ID>0009300000000</ID>
    <ProductProductionRuleID>W001</ProductProductionRuleID>
    <StartTime>2017-04-20T23:57:20</StartTime>
    <EndTime>2017-04-20T24:00:00</EndTime>
    </ProductionRequest>
  </ProductionSchedule>

这是我用来读取上述 XML 的代码

using System;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;

namespace XML
{
  class Program
  {
    static void Main(string[] args)
    {
     Console.WriteLine("Hello World!");
     string fullName = "F:\\Programming\\XML\\Example XML.xml";
     XmlDocument xreader = new XmlDocument();

     xreader.Load(fullName);
     XmlNode root = xreader.DocumentElement;
     XmlNodeList xnList1 = 
            xreader.SelectNodes("/ProductionSchedule/ProductionRequest/ID");


    }
  }
 }

我找不到这个问题的原因。任何人都可以在这方面帮助我。期待宝贵的意见。

最佳答案

您的 xml 包含命名空间 http://www.wbf.org/xml/b2mml-v02在根级节点 <ProductionSchedule>

并且您正在使用 XPath 表达式 /ProductionSchedule/ProductionRequest/ID但是这个 XPath 表达式不适合这个 xml 文档,这就是为什么你无法获得任何所需的值。

您需要使用下面的 XPath 表达式来获取所有 <ProductionRequest> 的 id节点。

XmlNodeList xnList1 = xreader.SelectNodes("//*[name()='ProductionSchedule']/*[name()='ProductionRequest']/*[name()='ID']");

或者您可以手动添加命名空间,例如

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xreader.NameTable);
nsmgr.AddNamespace("x", "http://www.wbf.org/xml/b2mml-v02");
XmlNodeList xnList1 = xreader.SelectNodes("//x:ProductionSchedule/x:ProductionRequest/x:ID", nsmgr);

最后,您可以阅读 id来自变量 xnList1 中的任何父节点喜欢

foreach (XmlNode id in xnList1)
{
    Console.WriteLine(id.InnerText);
}

输出:

enter image description here

关于c# - 在 C# 中使用 XPath 表达式读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957726/

相关文章:

c# - 如何从集合中获取Linq?

xml - 声明式查询大型 XML 文件/流

Android Spinner 下拉箭头不显示

xml - XSLT:如何只输出本地化数据?

c# - 如何跨项目和客户端自定义类库配置设置

c# - VS2010 Profiler 找不到符号

xml - 在 Powershell 中将 xml 转换为 csv 文件

xml - 根据属性名称提取 XML

python - 为什么 response.xpath ('//html' ) 的结果与 response.body 不同?

c# - RadioButton.Checked 错误 : Control. Checked 不能出现在 += 或 -= 的左侧