c# - 我在 C# 中使用 XPath 有什么问题?
问题描述
我正在尝试在 ac# 应用程序中进行一些抓取。
我正在尝试访问以下页面上的 4 条信息: https ://smstestbed.nist.gov/vds/current
- 创建时间
- 可用性
- 线性 X 和 Y 坐标
以下功能是我从远程加工工具轮询实时数据馈送的地方。我遇到的问题是,虽然我能够将“CreationTime”打印到终端,但我的 XPath 使用非常笨拙,而且据此链接似乎表明我应该能够在之后的 2 行中做我正在做的事情我的评论
“//这应该是访问数据的更好方法,但由于某种原因,第二行失败了”
不幸的是,我得到的AvailabilityNode为 Null。
public static void PollNIST()
{
string NISTSourceURL = "https://smstestbed.nist.gov/vds/current"; // Gives us a human friendly reference to the HTM
//-------------------------------- Current (mostly) Working Version---------------------------------------------------------------------------------
// Retrieve raw HTML
var NISTTargetURL = NISTSourceURL;
var NISTHttpClient = new HttpClient();
var NISTXMLRaw = NISTHttpClient.GetStringAsync(NISTTargetURL); // We now have all of the HTML / XML Data as a raw string
//Console.WriteLine(MazXMLRaw.Result); // Prints the resulting HTML to a terminal as a debug tool (Works)
XmlDocument CurNISTXML = new XmlDocument(); // Generate Blank XML Doc
CurNISTXML.LoadXml(NISTXMLRaw.Result); // This (".result") passes the actual string?, should then be loaded into new XML file
var elementHeader = CurNISTXML.GetElementsByTagName("Header");
var curNISTHeader = elementHeader.Item(0);
var creationTime = curNISTHeader.Attributes[0]; // We actually have the creationTime
string CurNISTTime = creationTime.InnerText; ; // //*[@id="mtconnect content"]/ul/li[1]
//This should be a far better way of accessing the data but for some reason the second line fails
XmlNode AvailabilityNode = CurNISTXML.SelectSingleNode("/table[1]/tbody/tr[1]"); //*[@id="mtconnect content"]/table[1]/tbody/tr[1]/td[7] // Xpath Availability
var CurNISTStatus = AvailabilityNode.InnerText; // //*[@id="mtconnect content"]/ul/li[1]
string CurNistX = ""; // //*[@id="mtconnect content"]/table[5]/tbody/tr/td[7]
string CurNistY = ""; // //*[@id="mtconnect content"]/table[6]/tbody/tr/td[7]
Console.WriteLine("-------BEGIN NIST DATA PACKET-------");
Console.WriteLine("NIST Time : " + creationTime.InnerText);
Console.WriteLine("NIST Status: " + CurNISTStatus);
Console.WriteLine("NIST X Pos.: " + CurNistX);
Console.WriteLine("NIST Y Pos.: " + CurNistY);
Console.WriteLine("--------END NIST DATA PACKET--------");
//var currentNIST = new NISTDataSet()// Create new instance ofNISTdata object
}
有任何想法吗?
解决方案
XPath 表达式
/table[1]/tbody/tr[1]
只有当文档的最外层元素是一个table
元素时才会成功,这似乎不太可能。我没有试图理解页面或代码的逻辑,但这看起来肯定是错误的。路径表达式开头的“/”从树的根中选择。
推荐阅读
- c++ - 在 C++17 中删除分配在堆上的向量的规范方法
- javascript - discord.js 机器人在尝试发送嵌入时报告 [object object]
- c# - 在运行时引用 Visual Studio 扩展项目中的类库
- python - 从python中的SQLITE表中删除第一行
- perforce - 有没有一种简单的方法可以让 perforce “自动”确保两个文件,在不同的路径下,总是包含相同的内容?
- powerbi - PowerBI 和过滤总和计算
- objective-c - ObjectiveC 项目中的 SwiftUI - 列表在预览中工作,而不是在运行时工作
- c++ - 选择 4 个随机数 printf
- angular - 如何在不使用 Promise 的情况下通过 HTTP 检索数据
- android - Flutter - 来自firebase的readData()导致该方法被调用为null