【问题标题】:C# XmlNode has ancestor typeC# XmlNode 具有祖先类型
【发布时间】: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>

【问题讨论】:

    标签: c# xmldocument xmlnode ancestor


    【解决方案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')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多