我当前在使用 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);
}
输出:
关于c# - 在 C# 中使用 XPath 表达式读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957726/