代码之家  ›  专栏  ›  技术社区  ›  alexmac

使用LINQ展平XML文件的简单方法

  •  1
  • alexmac  · 技术社区  · 17 年前

    使用LINQ有没有一种简单的方法来展平XML文件?

    我可以看到XSLT的许多方法,但我想知道LINQ的最佳选择是什么?

    我不能完全按照stackoverflow过滤chevron字符的方式来构建xml结构。但它是这样的

    --节点1

    --节点2

    我想和你在一起

    诺迪亚

    节点1

    节点2

    节点

    3 回复  |  直到 17 年前
        1
  •  1
  •   ehosca    14 年前

    使用扩展方法很容易做到:

    public static class XElementExtensions
    {
        public static string Path(this XElement xElement)
        {
            return PathInternal(xElement);
        }
    
        private static string PathInternal(XElement xElement)
        {
            if (xElement.Parent != null)
                return string.Concat(PathInternal(xElement.Parent), ".", xElement.Name.LocalName);
    
            return xElement.Name.LocalName;
        }
    }
    

    private static void Main()
    {
        string sb =@"<xml>
                    <nodeA>
                        <nodeA1>
                            <inner1/><inner2/>
                        </nodeA1>
                        <nodeA2/>
                    </nodeA>
                    <NodeB/>
                    </xml>";
    
        XDocument xDoc = XDocument.Parse(sb);
    
        var result = xDoc.Root.Descendants()
            .Select(r => new {Path = r.Path()});
    
        foreach (var p in result)
            Console.WriteLine(p.Path);
    }
    

    结果:

    xml.nodeA
    xml.nodeA.nodeA1
    xml.nodeA.nodeA1.inner1
    xml.nodeA.nodeA1.inner2
    xml.nodeA.nodeA2
    xml.NodeB
    
        2
  •  1
  •   svick Raja Nadar    14 年前

    好啊这取决于您想要的输出-对于XElement,您需要做一些工作来删除所有子节点等。但是,使用XmlDocument实际上非常简单:

    string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";
    
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    
    XmlDocument clone = new XmlDocument();
    XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
    foreach(XmlElement el in doc.SelectNodes("//*")) {
        root.AppendChild(clone.ImportNode(el, false));
    }
    Console.WriteLine(clone.OuterXml);
    

    产出:

    <xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
    

    [过去] XDocument具有子体()和子体节点(),它们可能会执行此任务。。。

        3
  •  0
  •   Guy    17 年前

    LINQPad 并查看“展平”的结果

    string xml = @"<xml><nodeA><nodeA1><inner1/><inner2/></nodeA1><nodeA2/></nodeA><NodeB/></xml>";
    
    XDocument doc = XDocument.Parse(xml);
    
    doc.Dump();
    doc.Root.Descendants().Dump();
    doc.Descendants().Dump();
    doc.Root.Descendants().Count().Dump();
    doc.Descendants().Count().Dump();