You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#技术实现:获取包含所有父标签的XML节点内容

获取XML节点内容并包含所有父标签(C#实现)

Got it, let's break down how to pull an XML node along with all its parent tags using C#. I'll use your sample XML (with a quick typo fix—notice the extra double quote in the Robinson Crusoe book entry? I'll correct that in the examples to avoid parsing errors).

First, here's the cleaned-up sample XML we'll work with:

<favorites>
  <movies>
    <movie title="The Godfather" year="1974" />
    <movie title="The Terminator" year="1984" />
    <movie title="Dark Knight" year="2008" />
  </movies>
  <books>
    <book title="1984" author="George Orwell" />
    <book title="Robinson Crusoe" author="Daniel Defoe"/>
    <book title="Frankenstein" author="Mary Shelly" />
  </books>
  <music>
    <artist title="Beatles" genre="rock" />
  </music>
</favorites>

方法1:使用XmlDocument(传统.NET API)

This approach uses the older but reliable XmlDocument class. We'll locate the target node, then traverse up through its parent nodes to build the full XML structure.

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // Load the XML (can also load from a file with XmlDocument.Load())
        string xmlContent = @"<favorites>
  <movies>
    <movie title=""The Godfather"" year=""1974"" />
    <movie title=""The Terminator"" year=""1984"" />
    <movie title=""Dark Knight"" year=""2008"" />
  </movies>
  <books>
    <book title=""1984"" author=""George Orwell"" />
    <book title=""Robinson Crusoe"" author=""Daniel Defoe""/>
    <book title=""Frankenstein"" author=""Mary Shelly"" />
  </books>
  <music>
    <artist title=""Beatles"" genre=""rock"" />
  </music>
</favorites>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlContent);

        // Find the target node (e.g., the movie with title "The Terminator")
        XmlNode targetNode = doc.SelectSingleNode("//movie[@title='The Terminator']");

        if (targetNode != null)
        {
            // Build the parent chain starting from the root
            XmlNode currentNode = targetNode;
            XmlDocument resultDoc = new XmlDocument();
            
            // Work our way up to the root, wrapping each level
            while (currentNode != null)
            {
                XmlNode newNode = resultDoc.ImportNode(currentNode, false);
                if (resultDoc.DocumentElement != null)
                {
                    newNode.AppendChild(resultDoc.DocumentElement);
                }
                resultDoc.DocumentElement = newNode;
                currentNode = currentNode.ParentNode;
            }

            // Output the full XML with parent tags
            Console.WriteLine(resultDoc.OuterXml);
        }
        else
        {
            Console.WriteLine("Target node not found.");
        }
    }
}

方法2:使用XDocument(LINQ to XML,更简洁)

If you prefer a more modern, LINQ-based approach, XDocument is perfect. It has built-in methods to grab all ancestor nodes in one go.

using System;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xmlContent = @"<favorites>
  <movies>
    <movie title=""The Godfather"" year=""1974"" />
    <movie title=""The Terminator"" year=""1984"" />
    <movie title=""Dark Knight"" year=""2008"" />
  </movies>
  <books>
    <book title=""1984"" author=""George Orwell"" />
    <book title=""Robinson Crusoe"" author=""Daniel Defoe""/>
    <book title=""Frankenstein"" author=""Mary Shelly"" />
  </books>
  <music>
    <artist title=""Beatles"" genre=""rock"" />
  </music>
</favorites>";
        XDocument doc = XDocument.Parse(xmlContent);

        // Find the target node (e.g., the book with title "1984")
        XElement targetElement = doc.Descendants("book")
                                    .FirstOrDefault(b => b.Attribute("title")?.Value == "1984");

        if (targetElement != null)
        {
            // Get all ancestor nodes plus the target itself, then reverse to build from root down
            var allNodes = targetElement.AncestorsAndSelf().Reverse();
            
            // Create a new XDocument with the full hierarchy
            XDocument resultDoc = new XDocument(
                new XElement(allNodes.First().Name,
                    allNodes.Skip(1).Select(n => new XElement(n.Name, n.Attributes()))
                )
            );

            // Output the result
            Console.WriteLine(resultDoc.ToString());
        }
        else
        {
            Console.WriteLine("Target node not found.");
        }
    }
}

关键说明

  • Typo Fix: Your original XML had an extra double quote in <book title = "Robinson Crusoe"" author="Daniel Defoe"/>—this will cause parsing errors, so make sure to correct that first.
  • Flexibility: Both methods let you target any node (movies, books, artists) by adjusting the XPath or LINQ query.
  • Output: The result will be a complete XML snippet that includes the target node wrapped in all its parent tags, up to the root.

内容的提问来源于stack exchange,提问作者Vladimir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:18:57