C# XmlNode 具有祖先类型

Posted

技术标签:

【中文标题】C# XmlNode 具有祖先类型【英文标题】:C# XmlNode has ancestor type 【发布时间】:2011-11-10 08:17:54 【问题描述】:

我有一个格式如下的 XmlDocument。如果我执行以下搜索

XmlNode title = xmlDoc.SelectNodes("//Book/Title[contains(., \"Title3\")]");

我会取回一个 XmlNode,它是一个标题。我如何确定该书是否属于出版物?我并不总是想假设 title.ParentNode.ParentNode.ParentNode 存在。应该有一种直观的说法:

if(title.hasAncestor("Publication") != null)

    // do whatever

任何帮助将不胜感激

<Publications>
    <Novel>
        <Book>
            <Title>Title1</Title>
            <Author>Author1</Author>
            <Year>2000</Year>
        </Book>
        <Book>
            <Title>Title2</Title>
            <Author>Author2</Author>
            <Year>2000</Year>
        </Book>
    </Novel>
    <History>
        <Book>
            <Title>Title3</Title>
            <Author>Author3</Author>
            <Year>2000</Year>
        </Book>
        <Book>
            <Title>Title4</Title>
            <Author>Author4</Author>
            <Year>2000</Year>
        </Book>
    </History>
</Publications>
<StudyGuides>
    <Math>
        <Book>
            <Title>Title5</Title>
            <Author>Author5</Author>
            <Year>2000</Year>
        </Book>
        <Book>
            <Title>Title6</Title>
            <Author>Author6</Author>
            <Year>2000</Year>
        </Book>
    </Math>
    <Science>
        <Book>
            <Title>Title7</Title>
            <Author>Author7</Author>
            <Year>2000</Year>
        </Book>
        <Book>
            <Title>Title8</Title>
            <Author>Author8</Author>
            <Year>2000</Year>
        </Book>
    </Science>
</StudyGuides>

【问题讨论】:

【参考方案1】:

您可以在 XPath 中使用 ancestor 轴来执行此操作:

//Book/Title[contains(., "Title3")][ancestor::Publications]

【讨论】:

感谢您的快速回复。我知道这将使我得到所有标题节点,其中包含“Title3”的innerText 在Publications 下。但是如果我有一个 XmlNode 以及在出版物或 StudyGuides 下确定之后要确定什么?也许我看错了?可能我需要查看下落的节点是否是 XmlDocument 中“Publications”下的子节点? @Koenyn 如果您将Title 节点作为XmlNode,则递归使用XmlNode.ParentNodetitleNode.SelectSingleNode(".[ancestor::Publications]") == null :) 谢谢。真的很感激。我不得不将其更改为 titleNode.SelectSingleNode("ancestor::Publications") == null【参考方案2】:
/Publications/*/Book/Title[contains(., 'Title3')]

【讨论】:

以上是关于C# XmlNode 具有祖先类型的主要内容,如果未能解决你的问题,请参考以下文章

C#如何在xmlnode中存储网站列表

如何在 C# 中从 XmlNode 读取属性值?

函数 RemoveChild(XmlNode 节点)在 C# 中失败

C# 中 XmlNode.SelectSingleNode(string xpath) 的正确用法是啥?

如何在 C# 中使用 XmlDocument 和 XmlNode 修改现有 XML 文件

c# .net 怎么将一个xml字符串 转换成一个xmlnode ,(不是xmldocument)