HTMLAgilityPack ChildNodes 索引有效,命名节点无效

发布于 2024-08-25 12:57:34 字数 503 浏览 3 评论 0原文

我正在使用 HTMLAgilityPack 解析 XML API 响应。我可以从 API 调用中选择结果项。 然后我循环遍历这些项目并希望将 ChildNode 写入表中。当我选择 ChildNodes 通过这样说:

sItemId = dnItem.ChildNodes(0).innertext

我得到了正确的 itemId 结果。但是当我尝试时:

sItemId = dnItem.ChildNodes("itemId").innertext

我得到“引用的对象的值为‘Nothing’。”

我尝试过“itemID[1]”、“/itemId[1]”和各种字符串。我尝试过 SelectSingleNode 和 ChildNodes.Item("itemId").innertext。唯一有效的方法是使用索引。

使用索引的问题在于,有时结果中会省略子元素,从而导致索引失效。

有人知道我做错了什么吗?

I am parsing an XML API response with HTMLAgilityPack. I am able to select the result items from the API call.
Then I loop through the items and want to write the ChildNodes to a table. When I select
ChildNodes by saying something like:

sItemId = dnItem.ChildNodes(0).innertext

I get the proper itemId result. But when I try:

sItemId = dnItem.ChildNodes("itemId").innertext

I get "Referenced object has a value of 'Nothing'."

I have tried "itemID[1]", "/itemId[1]" and a veriety of strings. I have tried SelectSingleNode and ChildNodes.Item("itemId").innertext. The only one that has worked is using the index.

The problem with using the index is that sometimes child elements are omitted in the results and that throw off the index.

Anybody know what I am doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

脸赞 2024-09-01 12:57:34
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@webHTMLeditor.TextXhtml);
HtmlNodeCollection tableRows = htmlDoc.DocumentNode.SelectNodes("//tr");
for (int i = 0; i < tableRows.Count; i++)
{
    HtmlNode tr = tableRows[i];

    HtmlNode[] td = new HtmlNode[2];
    string xpath = tr.XPath + "//td";
    HtmlNodeCollection cellRows = tr.SelectNodes(@xpath);
    //td[0] = tr.ChildNodes[1];                
    //td[1] = tr.ChildNodes[3];
    try
    {
        td[0] = cellRows[0];
        td[1] = cellRows[1];
    }
    catch (Exception)
    { }
    //etc   
}

该代码用于从表中逐行、按每行单元格提取数据。
我使用了现有的 xpath,并根据我的需要对其进行了更改。
祝你好运!

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@webHTMLeditor.TextXhtml);
HtmlNodeCollection tableRows = htmlDoc.DocumentNode.SelectNodes("//tr");
for (int i = 0; i < tableRows.Count; i++)
{
    HtmlNode tr = tableRows[i];

    HtmlNode[] td = new HtmlNode[2];
    string xpath = tr.XPath + "//td";
    HtmlNodeCollection cellRows = tr.SelectNodes(@xpath);
    //td[0] = tr.ChildNodes[1];                
    //td[1] = tr.ChildNodes[3];
    try
    {
        td[0] = cellRows[0];
        td[1] = cellRows[1];
    }
    catch (Exception)
    { }
    //etc   
}

The code is used to extract data from a table, row by row, by cell per row.
I used the existing xpath and I altered it acording to my needs.
Good luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文