简体   繁体   English

阅读和遍历C#中的xml元素

[英]Reading and iterating through xml elements in C#

I am just started working with C# language and looking for a way to iterate though the elements and child elements from a xml file. 我刚刚开始使用C#语言,正在寻找一种方法来遍历xml文件中的元素和子元素。

My xml Looks like this- 我的xml看起来像这样-

  <ServerList>
     <server name = "serverName1" username ="username" password ="password">
      <serviceName>serviceName</serviceName>
      <serviceName>serviceName</serviceName>
      <serviceName>serviceName</serviceName>
   </server>
<server name = "serverName2" username ="username" password = "password">
       <serviceName>serviceName</serviceName>
       <serviceName>serviceName</serviceName>
  </server>
<ServerList>

I am just looking for a approach where i can go through the first server elements and its child elements and than the next server elements and its child. 我只是在寻找一种方法,让我可以遍历第一个服务器元素及其子元素,而不是下一个服务器元素及其子元素。

You could use LINQ to XML as a straightforward approach: 您可以使用LINQ to XML作为一种简单的方法:

XDocument xdoc = XDocument.Load("myXmlFile.xml");

var servers = xdoc.Descendants("server"); 
for (var server in servers) 
{
    var children = server.Elements(); 
    for (var child in children)
    {
        // Do what you want with the server and child here
    }
}

If there's much more information you need, you might want to consider using XML deserialization. 如果需要更多信息,则可能需要考虑使用XML反序列化。 This will allow you to define classes that map to nodes in your XML schema, deserialize the XML into a graph of strongly typed objects that you can then iterate, filter, transform etc. If you do decide on this approach, I would suggest using YAXLib , because the BCL XML serializer kind of sucks. 这将允许您定义映射到XML模式中的节点的类,将XML反序列化为强类型对象的图,然后可以对其进行迭代,过滤,转换等。如果您决定采用这种方法,建议您使用YAXLib ,因为BCL XML序列化程序有点烂。

Descendants is fine, here's a recursive approach anyway 后代很好,这还是一种递归方法

class Program
{
    static void Main(string[] args)
    {
        XElement x = XElement.Load("XMLFile1.xml");
        recursive(x.Elements());
        Console.ReadKey();
    }

    private static void recursive(IEnumerable<XElement> elements)
    {
        foreach (XElement n in elements)
        {
            Console.WriteLine(n.Name);
            Console.WriteLine("--");
            if (n.Descendants().Any())
            {
                recursive(n.Elements());
            }
            else
            {
             Console.WriteLine(n.Value.ToString());// End of node (leaf)
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM